]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
989faf9c7385625ead43d2dd8c610bfbddec88cd
[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 #include "xline.h"
58
59 #ifdef GCC3
60 #define nspace __gnu_cxx
61 #else
62 #define nspace std
63 #endif
64
65 int LogLevel = DEFAULT;
66 char ServerName[MAXBUF];
67 char Network[MAXBUF];
68 char ServerDesc[MAXBUF];
69 char AdminName[MAXBUF];
70 char AdminEmail[MAXBUF];
71 char AdminNick[MAXBUF];
72 char diepass[MAXBUF];
73 char restartpass[MAXBUF];
74 char motd[MAXBUF];
75 char rules[MAXBUF];
76 char list[MAXBUF];
77 char PrefixQuit[MAXBUF];
78 char DieValue[MAXBUF];
79 int debugging =  0;
80 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
81 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
82 int DieDelay  =  5;
83 time_t startup_time = time(NULL);
84 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
85 time_t nb_start = 0;
86
87 extern vector<Module*> modules;
88 std::vector<std::string> module_names;
89 extern vector<ircd_module*> factory;
90 std::vector<int> fd_reap;
91
92 extern int MODCOUNT;
93
94 bool nofork = false;
95
96 namespace nspace
97 {
98         template<> struct nspace::hash<in_addr>
99         {
100                 size_t operator()(const struct in_addr &a) const
101                 {
102                         size_t q;
103                         memcpy(&q,&a,sizeof(size_t));
104                         return q;
105                 }
106         };
107
108         template<> struct nspace::hash<string>
109         {
110                 size_t operator()(const string &s) const
111                 {
112                         char a[MAXBUF];
113                         static struct hash<const char *> strhash;
114                         strcpy(a,s.c_str());
115                         strlower(a);
116                         return strhash(a);
117                 }
118         };
119 }       
120
121
122 struct StrHashComp
123 {
124
125         bool operator()(const string& s1, const string& s2) const
126         {
127                 char a[MAXBUF],b[MAXBUF];
128                 strcpy(a,s1.c_str());
129                 strcpy(b,s2.c_str());
130                 return (strcasecmp(a,b) == 0);
131         }
132
133 };
134
135 struct InAddr_HashComp
136 {
137
138         bool operator()(const in_addr &s1, const in_addr &s2) const
139         {
140                 size_t q;
141                 size_t p;
142                 
143                 memcpy(&q,&s1,sizeof(size_t));
144                 memcpy(&p,&s2,sizeof(size_t));
145                 
146                 return (q == p);
147         }
148
149 };
150
151
152 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
153 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
154 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
155 typedef std::deque<command_t> command_table;
156
157 serverrec* me[32];
158
159 FILE *log_file;
160
161 user_hash clientlist;
162 chan_hash chanlist;
163 user_hash whowas;
164 command_table cmdlist;
165 file_cache MOTD;
166 file_cache RULES;
167 address_cache IP;
168
169 ClassVector Classes;
170
171 struct linger linger = { 0 };
172 char bannerBuffer[MAXBUF];
173 int boundPortCount = 0;
174 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
175 int defaultRoute = 0;
176
177 connection C;
178
179 long MyKey = C.GenKey();
180
181 /* prototypes */
182
183 int has_channel(userrec *u, chanrec *c);
184 int usercount(chanrec *c);
185 int usercount_i(chanrec *c);
186 void update_stats_l(int fd,int data_out);
187 char* Passwd(userrec *user);
188 bool IsDenied(userrec *user);
189 void AddWhoWas(userrec* u);
190
191 std::vector<long> auth_cookies;
192 std::stringstream config_f(stringstream::in | stringstream::out);
193
194
195
196 long GetRevision()
197 {
198         char Revision[] = "$Revision$";
199         char *s1 = Revision;
200         char *savept;
201         char *v1 = strtok_r(s1," ",&savept);
202         s1 = savept;
203         char *v2 = strtok_r(s1," ",&savept);
204         s1 = savept;
205         return (long)(atof(v2)*10000);
206 }
207
208
209 std::string getservername()
210 {
211         return ServerName;
212 }
213
214 std::string getserverdesc()
215 {
216         return ServerDesc;
217 }
218
219 std::string getnetworkname()
220 {
221         return Network;
222 }
223
224 std::string getadminname()
225 {
226         return AdminName;
227 }
228
229 std::string getadminemail()
230 {
231         return AdminEmail;
232 }
233
234 std::string getadminnick()
235 {
236         return AdminNick;
237 }
238
239 void log(int level,char *text, ...)
240 {
241         char textbuffer[MAXBUF];
242         va_list argsPtr;
243         time_t rawtime;
244         struct tm * timeinfo;
245         if (level < LogLevel)
246                 return;
247
248         time(&rawtime);
249         timeinfo = localtime (&rawtime);
250
251         if (log_file)
252         {
253                 char b[MAXBUF];
254                 va_start (argsPtr, text);
255                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
256                 va_end(argsPtr);
257                 strcpy(b,asctime(timeinfo));
258                 b[strlen(b)-1] = ':';
259                 fprintf(log_file,"%s %s\n",b,textbuffer);
260                 if (nofork)
261                 {
262                         // nofork enabled? display it on terminal too
263                         printf("%s %s\n",b,textbuffer);
264                 }
265         }
266 }
267
268 void readfile(file_cache &F, const char* fname)
269 {
270   FILE* file;
271   char linebuf[MAXBUF];
272
273   log(DEBUG,"readfile: loading %s",fname);
274   F.clear();
275   file =  fopen(fname,"r");
276   if (file)
277   {
278         while (!feof(file))
279         {
280                 fgets(linebuf,sizeof(linebuf),file);
281                 linebuf[strlen(linebuf)-1]='\0';
282                 if (!strcmp(linebuf,""))
283                 {
284                         strcpy(linebuf,"  ");
285                 }
286                 if (!feof(file))
287                 {
288                         F.push_back(linebuf);
289                 }
290         }
291         fclose(file);
292   }
293   else
294   {
295           log(DEBUG,"readfile: failed to load file: %s",fname);
296   }
297   log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
298 }
299
300 void ReadConfig(void)
301 {
302   char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
303   ConnectClass c;
304
305   LoadConf(CONFIG_FILE,&config_f);
306   
307   ConfValue("server","name",0,ServerName,&config_f);
308   ConfValue("server","description",0,ServerDesc,&config_f);
309   ConfValue("server","network",0,Network,&config_f);
310   ConfValue("admin","name",0,AdminName,&config_f);
311   ConfValue("admin","email",0,AdminEmail,&config_f);
312   ConfValue("admin","nick",0,AdminNick,&config_f);
313   ConfValue("files","motd",0,motd,&config_f);
314   ConfValue("files","rules",0,rules,&config_f);
315   ConfValue("power","diepass",0,diepass,&config_f);
316   ConfValue("power","pause",0,pauseval,&config_f);
317   ConfValue("power","restartpass",0,restartpass,&config_f);
318   ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
319   ConfValue("die","value",0,DieValue,&config_f);
320   ConfValue("options","loglevel",0,dbg,&config_f);
321   ConfValue("options","netbuffersize",0,NB,&config_f);
322   NetBufferSize = atoi(NB);
323   if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
324   {
325         log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
326         NetBufferSize = 10240;
327   }
328   if (!strcmp(dbg,"debug"))
329         LogLevel = DEBUG;
330   if (!strcmp(dbg,"verbose"))
331         LogLevel = VERBOSE;
332   if (!strcmp(dbg,"default"))
333         LogLevel = DEFAULT;
334   if (!strcmp(dbg,"sparse"))
335         LogLevel = SPARSE;
336   if (!strcmp(dbg,"none"))
337         LogLevel = NONE;
338   readfile(MOTD,motd);
339   log(DEBUG,"Reading message of the day");
340   readfile(RULES,rules);
341   log(DEBUG,"Reading connect classes");
342   Classes.clear();
343   for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
344   {
345         strcpy(Value,"");
346         ConfValue("connect","allow",i,Value,&config_f);
347         ConfValue("connect","timeout",i,timeout,&config_f);
348         ConfValue("connect","flood",i,flood,&config_f);
349         if (strcmp(Value,""))
350         {
351                 strcpy(c.host,Value);
352                 c.type = CC_ALLOW;
353                 strcpy(Value,"");
354                 ConfValue("connect","password",i,Value,&config_f);
355                 strcpy(c.pass,Value);
356                 c.registration_timeout = 90; // default is 2 minutes
357                 c.flood = atoi(flood);
358                 if (atoi(timeout)>0)
359                 {
360                         c.registration_timeout = atoi(timeout);
361                 }
362                 Classes.push_back(c);
363                 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
364         }
365         else
366         {
367                 ConfValue("connect","deny",i,Value,&config_f);
368                 strcpy(c.host,Value);
369                 c.type = CC_DENY;
370                 Classes.push_back(c);
371                 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
372         }
373         
374   }
375 }
376
377 /* write formatted text to a socket, in same format as printf */
378
379 void Write(int sock,char *text, ...)
380 {
381   if (!text)
382   {
383         log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
384         return;
385   }
386   char textbuffer[MAXBUF];
387   va_list argsPtr;
388   char tb[MAXBUF];
389
390   va_start (argsPtr, text);
391   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
392   va_end(argsPtr);
393   sprintf(tb,"%s\r\n",textbuffer);
394   chop(tb);
395   if (sock != -1)
396   {
397         write(sock,tb,strlen(tb));
398         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
399   }
400 }
401
402 /* write a server formatted numeric response to a single socket */
403
404 void WriteServ(int sock, char* text, ...)
405 {
406   if (!text)
407   {
408         log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
409         return;
410   }
411   char textbuffer[MAXBUF],tb[MAXBUF];
412   va_list argsPtr;
413   va_start (argsPtr, text);
414
415   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
416   va_end(argsPtr);
417   sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
418   chop(tb);
419   if (sock != -1)
420   {
421         write(sock,tb,strlen(tb));
422         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
423   }
424 }
425
426 /* write text from an originating user to originating user */
427
428 void WriteFrom(int sock, userrec *user,char* text, ...)
429 {
430   if ((!text) || (!user))
431   {
432         log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
433         return;
434   }
435   char textbuffer[MAXBUF],tb[MAXBUF];
436   va_list argsPtr;
437   va_start (argsPtr, text);
438
439   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
440   va_end(argsPtr);
441   sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
442   chop(tb);
443   if (sock != -1)
444   {
445         write(sock,tb,strlen(tb));
446         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
447   }
448 }
449
450 /* write text to an destination user from a source user (e.g. user privmsg) */
451
452 void WriteTo(userrec *source, userrec *dest,char *data, ...)
453 {
454         if ((!dest) || (!data))
455         {
456                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
457                 return;
458         }
459         char textbuffer[MAXBUF],tb[MAXBUF];
460         va_list argsPtr;
461         va_start (argsPtr, data);
462         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
463         va_end(argsPtr);
464         chop(tb);
465
466         // if no source given send it from the server.
467         if (!source)
468         {
469                 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
470         }
471         else
472         {
473                 WriteFrom(dest->fd,source,"%s",textbuffer);
474         }
475 }
476
477 /* write formatted text from a source user to all users on a channel
478  * including the sender (NOT for privmsg, notice etc!) */
479
480 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
481 {
482         if ((!Ptr) || (!user) || (!text))
483         {
484                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
485                 return;
486         }
487         char textbuffer[MAXBUF];
488         va_list argsPtr;
489         va_start (argsPtr, text);
490         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
491         va_end(argsPtr);
492         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
493         {
494                 if (has_channel(i->second,Ptr))
495                 {
496                         WriteTo(user,i->second,"%s",textbuffer);
497                 }
498         }
499 }
500
501 /* write formatted text from a source user to all users on a channel
502  * including the sender (NOT for privmsg, notice etc!) doesnt send to
503  * users on remote servers */
504
505 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
506 {
507         if ((!Ptr) || (!text))
508         {
509                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
510                 return;
511         }
512         char textbuffer[MAXBUF];
513         va_list argsPtr;
514         va_start (argsPtr, text);
515         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
516         va_end(argsPtr);
517         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
518         {
519                 if (has_channel(i->second,Ptr))
520                 {
521                         if (i->second->fd != -1)
522                         {
523                                 if (!user)
524                                 {
525                                         WriteServ(i->second->fd,"%s",textbuffer);
526                                 }
527                                 else
528                                 {
529                                         WriteTo(user,i->second,"%s",textbuffer);
530                                 }
531                         }       
532                 }
533         }
534 }
535
536
537 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
538 {
539         if ((!Ptr) || (!user) || (!text))
540         {
541                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
542                 return;
543         }
544         char textbuffer[MAXBUF];
545         va_list argsPtr;
546         va_start (argsPtr, text);
547         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
548         va_end(argsPtr);
549         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
550         {
551                 if (i->second)
552                 {
553                         if (has_channel(i->second,Ptr))
554                         {
555                                 WriteServ(i->second->fd,"%s",textbuffer);
556                         }
557                 }
558         }
559 }
560
561
562 /* write formatted text from a source user to all users on a channel except
563  * for the sender (for privmsg etc) */
564
565 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
566 {
567         if ((!Ptr) || (!user) || (!text))
568         {
569                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
570                 return;
571         }
572         char textbuffer[MAXBUF];
573         va_list argsPtr;
574         va_start (argsPtr, text);
575         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
576         va_end(argsPtr);
577
578         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
579         {
580                 if (i->second)
581                 {
582                         if (has_channel(i->second,Ptr) && (user != i->second))
583                         {
584                                 WriteTo(user,i->second,"%s",textbuffer);
585                         }
586                 }
587         }
588 }
589
590
591 std::string GetServerDescription(char* servername)
592 {
593         for (int j = 0; j < 32; j++)
594         {
595                 if (me[j] != NULL)
596                 {
597                         for (int k = 0; k < me[j]->connectors.size(); k++)
598                         {
599                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
600                                 {
601                                         return me[j]->connectors[k].GetDescription();
602                                 }
603                         }
604                 }
605                 return ServerDesc; // not a remote server that can be found, it must be me.
606         }
607 }
608
609
610 /* write a formatted string to all users who share at least one common
611  * channel, including the source user e.g. for use in NICK */
612
613 void WriteCommon(userrec *u, char* text, ...)
614 {
615         if (!u)
616         {
617                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
618                 return;
619         }
620
621         if (u->registered != 7) {
622                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
623                 return;
624         }
625         
626         char textbuffer[MAXBUF];
627         va_list argsPtr;
628         va_start (argsPtr, text);
629         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
630         va_end(argsPtr);
631
632         WriteFrom(u->fd,u,"%s",textbuffer);
633
634         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
635         {
636                 if (i->second)
637                 {
638                         if (common_channels(u,i->second) && (i->second != u))
639                         {
640                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
641                         }
642                 }
643         }
644 }
645
646 /* write a formatted string to all users who share at least one common
647  * channel, NOT including the source user e.g. for use in QUIT */
648
649 void WriteCommonExcept(userrec *u, char* text, ...)
650 {
651         if (!u)
652         {
653                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
654                 return;
655         }
656
657         if (u->registered != 7) {
658                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
659                 return;
660         }
661
662         char textbuffer[MAXBUF];
663         va_list argsPtr;
664         va_start (argsPtr, text);
665         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
666         va_end(argsPtr);
667
668         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
669         {
670                 if (i->second)
671                 {
672                         if ((common_channels(u,i->second)) && (u != i->second))
673                         {
674                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
675                         }
676                 }
677         }
678 }
679
680 void WriteOpers(char* text, ...)
681 {
682         if (!text)
683         {
684                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
685                 return;
686         }
687
688         char textbuffer[MAXBUF];
689         va_list argsPtr;
690         va_start (argsPtr, text);
691         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
692         va_end(argsPtr);
693
694         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
695         {
696                 if (i->second)
697                 {
698                         if (strchr(i->second->modes,'o'))
699                         {
700                                 if (strchr(i->second->modes,'s'))
701                                 {
702                                         // send server notices to all with +s
703                                         // (TODO: needs SNOMASKs)
704                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
705                                 }
706                         }
707                 }
708         }
709 }
710
711 // returns TRUE of any users on channel C occupy server 'servername'.
712
713 bool ChanAnyOnThisServer(chanrec *c,char* servername)
714 {
715         log(DEBUG,"ChanAnyOnThisServer");
716         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
717         {
718                 if (has_channel(i->second,c))
719                 {
720                         if (!strcasecmp(i->second->server,servername))
721                         {
722                                 return true;
723                         }
724                 }
725         }
726         return false;
727 }
728
729 // returns true if user 'u' shares any common channels with any users on server 'servername'
730
731 bool CommonOnThisServer(userrec* u,const char* servername)
732 {
733         log(DEBUG,"ChanAnyOnThisServer");
734         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
735         {
736                 if ((common_channels(u,i->second)) && (u != i->second))
737                 {
738                         if (!strcasecmp(i->second->server,servername))
739                         {
740                                 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
741                                 return true;
742                         }
743                 }
744         }
745         return false;
746 }
747
748
749 void NetSendToCommon(userrec* u, char* s)
750 {
751         char buffer[MAXBUF];
752         snprintf(buffer,MAXBUF,"%s",s);
753         
754         log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
755
756         for (int j = 0; j < 32; j++)
757         {
758                 if (me[j] != NULL)
759                 {
760                         for (int k = 0; k < me[j]->connectors.size(); k++)
761                         {
762                                 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
763                                 {
764                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
765                                 }
766                         }
767                 }
768         }
769 }
770
771
772 void NetSendToAll(char* s)
773 {
774         char buffer[MAXBUF];
775         snprintf(buffer,MAXBUF,"%s",s);
776         
777         log(DEBUG,"NetSendToAll: '%s'",s);
778
779         for (int j = 0; j < 32; j++)
780         {
781                 if (me[j] != NULL)
782                 {
783                         for (int k = 0; k < me[j]->connectors.size(); k++)
784                         {
785                                 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
786                         }
787                 }
788         }
789 }
790
791 void NetSendToAllAlive(char* s)
792 {
793         char buffer[MAXBUF];
794         snprintf(buffer,MAXBUF,"%s",s);
795         
796         log(DEBUG,"NetSendToAllAlive: '%s'",s);
797
798         for (int j = 0; j < 32; j++)
799         {
800                 if (me[j] != NULL)
801                 {
802                         for (int k = 0; k < me[j]->connectors.size(); k++)
803                         {
804                                 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
805                                 {
806                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
807                                 }
808                                 else
809                                 {
810                                         log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
811                                 }
812                         }
813                 }
814         }
815 }
816
817
818 void NetSendToOne(char* target,char* s)
819 {
820         char buffer[MAXBUF];
821         snprintf(buffer,MAXBUF,"%s",s);
822         
823         log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
824
825         for (int j = 0; j < 32; j++)
826         {
827                 if (me[j] != NULL)
828                 {
829                         for (int k = 0; k < me[j]->connectors.size(); k++)
830                         {
831                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
832                                 {
833                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
834                                 }
835                         }
836                 }
837         }
838 }
839
840 void NetSendToAllExcept(const char* target,char* s)
841 {
842         char buffer[MAXBUF];
843         snprintf(buffer,MAXBUF,"%s",s);
844         
845         log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
846         
847         for (int j = 0; j < 32; j++)
848         {
849                 if (me[j] != NULL)
850                 {
851                         for (int k = 0; k < me[j]->connectors.size(); k++)
852                         {
853                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
854                                 {
855                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
856                                 }
857                         }
858                 }
859         }
860 }
861
862
863 void WriteMode(const char* modes, int flags, const char* text, ...)
864 {
865         if ((!text) || (!modes) || (!flags))
866         {
867                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
868                 return;
869         }
870
871         char textbuffer[MAXBUF];
872         va_list argsPtr;
873         va_start (argsPtr, text);
874         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
875         va_end(argsPtr);
876
877         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
878         {
879                 if (i->second)
880                 {
881                         bool send_to_user = false;
882                         
883                         if (flags == WM_AND)
884                         {
885                                 send_to_user = true;
886                                 for (int n = 0; n < strlen(modes); n++)
887                                 {
888                                         if (!hasumode(i->second,modes[n]))
889                                         {
890                                                 send_to_user = false;
891                                                 break;
892                                         }
893                                 }
894                         }
895                         else if (flags == WM_OR)
896                         {
897                                 send_to_user = false;
898                                 for (int n = 0; n < strlen(modes); n++)
899                                 {
900                                         if (hasumode(i->second,modes[n]))
901                                         {
902                                                 send_to_user = true;
903                                                 break;
904                                         }
905                                 }
906                         }
907
908                         if (send_to_user)
909                         {
910                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
911                         }
912                 }
913         }
914 }
915
916
917 void WriteWallOps(userrec *source, bool local_only, char* text, ...)  
918 {  
919         if ((!text) || (!source))
920         {
921                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
922                 return;
923         }
924
925         int i = 0;  
926         char textbuffer[MAXBUF];  
927         va_list argsPtr;  
928         va_start (argsPtr, text);  
929         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
930         va_end(argsPtr);  
931   
932         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
933         {
934                 if (i->second)
935                 {
936                         if (strchr(i->second->modes,'w'))
937                         {
938                                 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
939                         }
940                 }
941         }
942
943         if (!local_only)
944         {
945                 char buffer[MAXBUF];
946                 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
947                 NetSendToAll(buffer);
948         }
949 }  
950
951 /* convert a string to lowercase. Note following special circumstances
952  * taken from RFC 1459. Many "official" server branches still hold to this
953  * rule so i will too;
954  *
955  *  Because of IRC's scandanavian origin, the characters {}| are
956  *  considered to be the lower case equivalents of the characters []\,
957  *  respectively. This is a critical issue when determining the
958  *  equivalence of two nicknames.
959  */
960
961 void strlower(char *n)
962 {
963         if (!n)
964         {
965                 return;
966         }
967         for (int i = 0; i != strlen(n); i++)
968         {
969                 n[i] = tolower(n[i]);
970                 if (n[i] == '[')
971                         n[i] = '{';
972                 if (n[i] == ']')
973                         n[i] = '}';
974                 if (n[i] == '\\')
975                         n[i] = '|';
976         }
977 }
978
979
980
981 /* Find a user record by nickname and return a pointer to it */
982
983 userrec* Find(string nick)
984 {
985         user_hash::iterator iter = clientlist.find(nick);
986
987         if (iter == clientlist.end())
988                 /* Couldn't find it */
989                 return NULL;
990
991         return iter->second;
992 }
993
994 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
995 {
996         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
997         {
998                 if (i->second)
999                 {
1000                         if (i->second->fd == fd)
1001                         {
1002                                 i->second->bytes_out+=data_out;
1003                                 i->second->cmds_out++;
1004                         }
1005                 }
1006         }
1007 }
1008
1009
1010 /* find a channel record by channel name and return a pointer to it */
1011
1012 chanrec* FindChan(const char* chan)
1013 {
1014         if (!chan)
1015         {
1016                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1017                 return NULL;
1018         }
1019
1020         chan_hash::iterator iter = chanlist.find(chan);
1021
1022         if (iter == chanlist.end())
1023                 /* Couldn't find it */
1024                 return NULL;
1025
1026         return iter->second;
1027 }
1028
1029
1030 void purge_empty_chans(void)
1031 {
1032         int go_again = 1, purge = 0;
1033         
1034         while (go_again)
1035         {
1036                 go_again = 0;
1037                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1038                 {
1039                         if (i->second) {
1040                                 if (!usercount(i->second))
1041                                 {
1042                                         /* kill the record */
1043                                         if (i != chanlist.end())
1044                                         {
1045                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1046                                                 delete i->second;
1047                                                 chanlist.erase(i);
1048                                                 go_again = 1;
1049                                                 purge++;
1050                                                 break;
1051                                         }
1052                                 }
1053                                 else
1054                                 {
1055                                         log(DEBUG,"skipped purge for %s",i->second->name);
1056                                 }
1057                         }
1058                 }
1059         }
1060         log(DEBUG,"completed channel purge, killed %d",purge);
1061 }
1062
1063
1064 char scratch[MAXBUF];
1065 char sparam[MAXBUF];
1066
1067 char* chanmodes(chanrec *chan)
1068 {
1069         if (!chan)
1070         {
1071                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1072                 strcpy(scratch,"");
1073                 return scratch;
1074         }
1075
1076         strcpy(scratch,"");
1077         strcpy(sparam,"");
1078         if (chan->noexternal)
1079         {
1080                 strncat(scratch,"n",MAXMODES);
1081         }
1082         if (chan->topiclock)
1083         {
1084                 strncat(scratch,"t",MAXMODES);
1085         }
1086         if (strcmp(chan->key,""))
1087         {
1088                 strncat(scratch,"k",MAXMODES);
1089         }
1090         if (chan->limit)
1091         {
1092                 strncat(scratch,"l",MAXMODES);
1093         }
1094         if (chan->inviteonly)
1095         {
1096                 strncat(scratch,"i",MAXMODES);
1097         }
1098         if (chan->moderated)
1099         {
1100                 strncat(scratch,"m",MAXMODES);
1101         }
1102         if (chan->secret)
1103         {
1104                 strncat(scratch,"s",MAXMODES);
1105         }
1106         if (chan->c_private)
1107         {
1108                 strncat(scratch,"p",MAXMODES);
1109         }
1110         if (strcmp(chan->key,""))
1111         {
1112                 strncat(sparam,chan->key,MAXBUF);
1113         }
1114         if (chan->limit)
1115         {
1116                 char foo[24];
1117                 sprintf(foo," %d",chan->limit);
1118                 strncat(sparam,foo,MAXBUF);
1119         }
1120         if (strlen(chan->custom_modes))
1121         {
1122                 strncat(scratch,chan->custom_modes,MAXMODES);
1123                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1124                 {
1125                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1126                         if (extparam != "")
1127                         {
1128                                 strncat(sparam," ",MAXBUF);
1129                                 strncat(sparam,extparam.c_str(),MAXBUF);
1130                         }
1131                 }
1132         }
1133         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1134         strncat(scratch,sparam,MAXMODES);
1135         return scratch;
1136 }
1137
1138
1139 /* compile a userlist of a channel into a string, each nick seperated by
1140  * spaces and op, voice etc status shown as @ and + */
1141
1142 void userlist(userrec *user,chanrec *c)
1143 {
1144         if ((!c) || (!user))
1145         {
1146                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1147                 return;
1148         }
1149
1150         sprintf(list,"353 %s = %s :", user->nick, c->name);
1151         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1152         {
1153                 if (has_channel(i->second,c))
1154                 {
1155                         if (isnick(i->second->nick))
1156                         {
1157                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1158                                 {
1159                                         /* user is +i, and source not on the channel, does not show
1160                                          * nick in NAMES list */
1161                                         continue;
1162                                 }
1163                                 strcat(list,cmode(i->second,c));
1164                                 strcat(list,i->second->nick);
1165                                 strcat(list," ");
1166                                 if (strlen(list)>(480-NICKMAX))
1167                                 {
1168                                         /* list overflowed into
1169                                          * multiple numerics */
1170                                         WriteServ(user->fd,list);
1171                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1172                                 }
1173                         }
1174                 }
1175         }
1176         /* if whats left in the list isnt empty, send it */
1177         if (list[strlen(list)-1] != ':')
1178         {
1179                 WriteServ(user->fd,list);
1180         }
1181 }
1182
1183 /* return a count of the users on a specific channel accounting for
1184  * invisible users who won't increase the count. e.g. for /LIST */
1185
1186 int usercount_i(chanrec *c)
1187 {
1188         int i = 0;
1189         int count = 0;
1190         
1191         if (!c)
1192         {
1193                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1194                 return 0;
1195         }
1196
1197         strcpy(list,"");
1198         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1199         {
1200                 if (i->second)
1201                 {
1202                         if (has_channel(i->second,c))
1203                         {
1204                                 if (isnick(i->second->nick))
1205                                 {
1206                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1207                                         {
1208                                                 /* user is +i, and source not on the channel, does not show
1209                                                  * nick in NAMES list */
1210                                                 continue;
1211                                         }
1212                                         count++;
1213                                 }
1214                         }
1215                 }
1216         }
1217         log(DEBUG,"usercount_i: %s %d",c->name,count);
1218         return count;
1219 }
1220
1221
1222 int usercount(chanrec *c)
1223 {
1224         int i = 0;
1225         int count = 0;
1226         
1227         if (!c)
1228         {
1229                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1230                 return 0;
1231         }
1232
1233         strcpy(list,"");
1234         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1235         {
1236                 if (i->second)
1237                 {
1238                         if (has_channel(i->second,c))
1239                         {
1240                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1241                                 {
1242                                         count++;
1243                                 }
1244                         }
1245                 }
1246         }
1247         log(DEBUG,"usercount: %s %d",c->name,count);
1248         return count;
1249 }
1250
1251
1252 /* add a channel to a user, creating the record for it if needed and linking
1253  * it to the user record */
1254
1255 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1256 {
1257         if ((!user) || (!cn))
1258         {
1259                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1260                 return 0;
1261         }
1262
1263         int i = 0;
1264         chanrec* Ptr;
1265         int created = 0;
1266         char cname[MAXBUF];
1267
1268         strncpy(cname,cn,MAXBUF);
1269         
1270         // we MUST declare this wherever we use FOREACH_RESULT
1271         int MOD_RESULT = 0;
1272
1273         if (strlen(cname) > CHANMAX-1)
1274         {
1275                 cname[CHANMAX-1] = '\0';
1276         }
1277
1278         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1279         
1280         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1281         {
1282                 return NULL; // already on the channel!
1283         }
1284
1285
1286         if (!FindChan(cname))
1287         {
1288                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1289                 if (MOD_RESULT) {
1290                         return NULL;
1291                 }
1292
1293                 /* create a new one */
1294                 log(DEBUG,"add_channel: creating: %s",cname);
1295                 {
1296                         chanlist[cname] = new chanrec();
1297
1298                         strcpy(chanlist[cname]->name, cname);
1299                         chanlist[cname]->topiclock = 1;
1300                         chanlist[cname]->noexternal = 1;
1301                         chanlist[cname]->created = time(NULL);
1302                         strcpy(chanlist[cname]->topic, "");
1303                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1304                         chanlist[cname]->topicset = 0;
1305                         Ptr = chanlist[cname];
1306                         log(DEBUG,"add_channel: created: %s",cname);
1307                         /* set created to 2 to indicate user
1308                          * is the first in the channel
1309                          * and should be given ops */
1310                         created = 2;
1311                 }
1312         }
1313         else
1314         {
1315                 /* channel exists, just fish out a pointer to its struct */
1316                 Ptr = FindChan(cname);
1317                 if (Ptr)
1318                 {
1319                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1320                         
1321                         // the override flag allows us to bypass channel modes
1322                         // and bans (used by servers)
1323                         if (!override)
1324                         {
1325                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1326                                 if (MOD_RESULT) {
1327                                         return NULL;
1328                                 }
1329                                 
1330                                 if (strcmp(Ptr->key,""))
1331                                 {
1332                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1333                                         if (!key)
1334                                         {
1335                                                 log(DEBUG,"add_channel: no key given in JOIN");
1336                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1337                                                 return NULL;
1338                                         }
1339                                         else
1340                                         {
1341                                                 log(DEBUG,"key at %p is %s",key,key);
1342                                                 if (strcasecmp(key,Ptr->key))
1343                                                 {
1344                                                         log(DEBUG,"add_channel: bad key given in JOIN");
1345                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1346                                                         return NULL;
1347                                                 }
1348                                         }
1349                                 }
1350                                 log(DEBUG,"add_channel: no key");
1351         
1352                                 if (Ptr->inviteonly)
1353                                 {
1354                                         log(DEBUG,"add_channel: channel is +i");
1355                                         if (user->IsInvited(Ptr->name))
1356                                         {
1357                                                 /* user was invited to channel */
1358                                                 /* there may be an optional channel NOTICE here */
1359                                         }
1360                                         else
1361                                         {
1362                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1363                                                 return NULL;
1364                                         }
1365                                 }
1366                                 log(DEBUG,"add_channel: channel is not +i");
1367         
1368                                 if (Ptr->limit)
1369                                 {
1370                                         if (usercount(Ptr) == Ptr->limit)
1371                                         {
1372                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1373                                                 return NULL;
1374                                         }
1375                                 }
1376                                 
1377                                 log(DEBUG,"add_channel: about to walk banlist");
1378         
1379                                 /* check user against the channel banlist */
1380                                 if (Ptr)
1381                                 {
1382                                         if (Ptr->bans.size())
1383                                         {
1384                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1385                                                 {
1386                                                         if (match(user->GetFullHost(),i->data))
1387                                                         {
1388                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1389                                                                 return NULL;
1390                                                         }
1391                                                 }
1392                                         }
1393                                 }
1394                                 
1395                                 log(DEBUG,"add_channel: bans checked");
1396                                 
1397
1398                                 if ((Ptr) && (user))
1399                                 {
1400                                         user->RemoveInvite(Ptr->name);
1401                                 }
1402         
1403                                 log(DEBUG,"add_channel: invites removed");
1404
1405                         }
1406                         else
1407                         {
1408                                 log(DEBUG,"Overridden checks");
1409                         }
1410
1411                         
1412                 }
1413                 created = 1;
1414         }
1415
1416         log(DEBUG,"Passed channel checks");
1417         
1418         for (int i =0; i != MAXCHANS; i++)
1419         {
1420                 log(DEBUG,"Check location %d",i);
1421                 if (user->chans[i].channel == NULL)
1422                 {
1423                         log(DEBUG,"Adding into their channel list at location %d",i);
1424
1425                         if (created == 2) 
1426                         {
1427                                 /* first user in is given ops */
1428                                 user->chans[i].uc_modes = UCMODE_OP;
1429                         }
1430                         else
1431                         {
1432                                 user->chans[i].uc_modes = 0;
1433                         }
1434                         user->chans[i].channel = Ptr;
1435                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1436                         
1437                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1438                         {
1439                                 // use the stamdard J token with no privilages.
1440                                 char buffer[MAXBUF];
1441                                 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1442                                 NetSendToAll(buffer);
1443                         }
1444
1445                         log(DEBUG,"Sent JOIN to client");
1446
1447                         if (Ptr->topicset)
1448                         {
1449                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1450                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1451                         }
1452                         userlist(user,Ptr);
1453                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1454                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1455                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1456                         FOREACH_MOD OnUserJoin(user,Ptr);
1457                         return Ptr;
1458                 }
1459         }
1460         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1461         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1462         return NULL;
1463 }
1464
1465 /* remove a channel from a users record, and remove the record from memory
1466  * if the channel has become empty */
1467
1468 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1469 {
1470         if ((!user) || (!cname))
1471         {
1472                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1473                 return NULL;
1474         }
1475
1476         chanrec* Ptr;
1477         int created = 0;
1478
1479         if ((!cname) || (!user))
1480         {
1481                 return NULL;
1482         }
1483
1484         Ptr = FindChan(cname);
1485         
1486         if (!Ptr)
1487         {
1488                 return NULL;
1489         }
1490
1491         FOREACH_MOD OnUserPart(user,Ptr);
1492         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1493         
1494         for (int i =0; i != MAXCHANS; i++)
1495         {
1496                 /* zap it from the channel list of the user */
1497                 if (user->chans[i].channel == Ptr)
1498                 {
1499                         if (reason)
1500                         {
1501                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1502
1503                                 if (!local)
1504                                 {
1505                                         char buffer[MAXBUF];
1506                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1507                                         NetSendToAll(buffer);
1508                                 }
1509
1510                                 
1511                         }
1512                         else
1513                         {
1514                                 if (!local)
1515                                 {
1516                                         char buffer[MAXBUF];
1517                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1518                                         NetSendToAll(buffer);
1519                                 }
1520                         
1521                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1522                         }
1523                         user->chans[i].uc_modes = 0;
1524                         user->chans[i].channel = NULL;
1525                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1526                         break;
1527                 }
1528         }
1529         
1530         /* if there are no users left on the channel */
1531         if (!usercount(Ptr))
1532         {
1533                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1534
1535                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1536
1537                 /* kill the record */
1538                 if (iter != chanlist.end())
1539                 {
1540                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1541                         delete iter->second;
1542                         chanlist.erase(iter);
1543                 }
1544         }
1545 }
1546
1547
1548 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1549 {
1550         if ((!src) || (!user) || (!Ptr) || (!reason))
1551         {
1552                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1553                 return;
1554         }
1555
1556         int i = 0;
1557         int created = 0;
1558
1559         if ((!Ptr) || (!user) || (!src))
1560         {
1561                 return;
1562         }
1563
1564         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1565
1566         if (!has_channel(user,Ptr))
1567         {
1568                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1569                 return;
1570         }
1571         if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1572         {
1573                 if (cstatus(src,Ptr) == STATUS_HOP)
1574                 {
1575                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1576                 }
1577                 else
1578                 {
1579                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1580                 }
1581                 
1582                 return;
1583         }
1584         
1585         for (int i =0; i != MAXCHANS; i++)
1586         {
1587                 /* zap it from the channel list of the user */
1588                 if (user->chans[i].channel)
1589                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1590                 {
1591                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1592                         user->chans[i].uc_modes = 0;
1593                         user->chans[i].channel = NULL;
1594                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1595                         break;
1596                 }
1597         }
1598         
1599         /* if there are no users left on the channel */
1600         if (!usercount(Ptr))
1601         {
1602                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1603
1604                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1605
1606                 /* kill the record */
1607                 if (iter != chanlist.end())
1608                 {
1609                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1610                         delete iter->second;
1611                         chanlist.erase(iter);
1612                 }
1613         }
1614 }
1615
1616
1617
1618
1619 /* This function pokes and hacks at a parameter list like the following:
1620  *
1621  * PART #winbot, #darkgalaxy :m00!
1622  *
1623  * to turn it into a series of individual calls like this:
1624  *
1625  * PART #winbot :m00!
1626  * PART #darkgalaxy :m00!
1627  *
1628  * The seperate calls are sent to a callback function provided by the caller
1629  * (the caller will usually call itself recursively). The callback function
1630  * must be a command handler. Calling this function on a line with no list causes
1631  * no action to be taken. You must provide a starting and ending parameter number
1632  * where the range of the list can be found, useful if you have a terminating
1633  * parameter as above which is actually not part of the list, or parameters
1634  * before the actual list as well. This code is used by many functions which
1635  * can function as "one to list" (see the RFC) */
1636
1637 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1638 {
1639         char plist[MAXBUF];
1640         char *param;
1641         char *pars[32];
1642         char blog[32][MAXBUF];
1643         char blog2[32][MAXBUF];
1644         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1645         char keystr[MAXBUF];
1646         char moo[MAXBUF];
1647
1648         for (int i = 0; i <32; i++)
1649                 strcpy(blog[i],"");
1650
1651         for (int i = 0; i <32; i++)
1652                 strcpy(blog2[i],"");
1653
1654         strcpy(moo,"");
1655         for (int i = 0; i <10; i++)
1656         {
1657                 if (!parameters[i])
1658                 {
1659                         parameters[i] = moo;
1660                 }
1661         }
1662         if (joins)
1663         {
1664                 if (pcnt > 1) /* we have a key to copy */
1665                 {
1666                         strcpy(keystr,parameters[1]);
1667                 }
1668         }
1669
1670         if (!parameters[start])
1671         {
1672                 return 0;
1673         }
1674         if (!strchr(parameters[start],','))
1675         {
1676                 return 0;
1677         }
1678         strcpy(plist,"");
1679         for (int i = start; i <= end; i++)
1680         {
1681                 if (parameters[i])
1682                 {
1683                         strcat(plist,parameters[i]);
1684                 }
1685         }
1686         
1687         j = 0;
1688         param = plist;
1689
1690         t = strlen(plist);
1691         for (int i = 0; i < t; i++)
1692         {
1693                 if (plist[i] == ',')
1694                 {
1695                         plist[i] = '\0';
1696                         strcpy(blog[j++],param);
1697                         param = plist+i+1;
1698                         if (j>20)
1699                         {
1700                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1701                                 return 1;
1702                         }
1703                 }
1704         }
1705         strcpy(blog[j++],param);
1706         total = j;
1707
1708         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1709         {
1710                 strcat(keystr,",");
1711         }
1712         
1713         if ((joins) && (keystr))
1714         {
1715                 if (strchr(keystr,','))
1716                 {
1717                         j = 0;
1718                         param = keystr;
1719                         t2 = strlen(keystr);
1720                         for (int i = 0; i < t2; i++)
1721                         {
1722                                 if (keystr[i] == ',')
1723                                 {
1724                                         keystr[i] = '\0';
1725                                         strcpy(blog2[j++],param);
1726                                         param = keystr+i+1;
1727                                 }
1728                         }
1729                         strcpy(blog2[j++],param);
1730                         total2 = j;
1731                 }
1732         }
1733
1734         for (j = 0; j < total; j++)
1735         {
1736                 if (blog[j])
1737                 {
1738                         pars[0] = blog[j];
1739                 }
1740                 for (q = end; q < pcnt-1; q++)
1741                 {
1742                         if (parameters[q+1])
1743                         {
1744                                 pars[q-end+1] = parameters[q+1];
1745                         }
1746                 }
1747                 if ((joins) && (parameters[1]))
1748                 {
1749                         if (pcnt > 1)
1750                         {
1751                                 pars[1] = blog2[j];
1752                         }
1753                         else
1754                         {
1755                                 pars[1] = NULL;
1756                         }
1757                 }
1758                 /* repeatedly call the function with the hacked parameter list */
1759                 if ((joins) && (pcnt > 1))
1760                 {
1761                         if (pars[1])
1762                         {
1763                                 // pars[1] already set up and containing key from blog2[j]
1764                                 fn(pars,2,u);
1765                         }
1766                         else
1767                         {
1768                                 pars[1] = parameters[1];
1769                                 fn(pars,2,u);
1770                         }
1771                 }
1772                 else
1773                 {
1774                         fn(pars,pcnt-(end-start),u);
1775                 }
1776         }
1777
1778         return 1;
1779 }
1780
1781
1782
1783 void kill_link(userrec *user,const char* r)
1784 {
1785         user_hash::iterator iter = clientlist.find(user->nick);
1786         
1787         char reason[MAXBUF];
1788         
1789         strncpy(reason,r,MAXBUF);
1790
1791         if (strlen(reason)>MAXQUIT)
1792         {
1793                 reason[MAXQUIT-1] = '\0';
1794         }
1795
1796         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1797         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1798         log(DEBUG,"closing fd %d",user->fd);
1799
1800         /* bugfix, cant close() a nonblocking socket (sux!) */
1801         if (user->registered == 7) {
1802                 FOREACH_MOD OnUserQuit(user);
1803                 WriteCommonExcept(user,"QUIT :%s",reason);
1804
1805                 // Q token must go to ALL servers!!!
1806                 char buffer[MAXBUF];
1807                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1808                 NetSendToAll(buffer);
1809         }
1810
1811         /* push the socket on a stack of sockets due to be closed at the next opportunity
1812          * 'Client exited' is an exception to this as it means the client side has already
1813          * closed the socket, we don't need to do it.
1814          */
1815         fd_reap.push_back(user->fd);
1816         
1817         bool do_purge = false;
1818         
1819         if (user->registered == 7) {
1820                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1821                 AddWhoWas(user);
1822         }
1823
1824         if (iter != clientlist.end())
1825         {
1826                 log(DEBUG,"deleting user hash value %d",iter->second);
1827                 if ((iter->second) && (user->registered == 7)) {
1828                         delete iter->second;
1829                 }
1830                 clientlist.erase(iter);
1831         }
1832
1833         if (user->registered == 7) {
1834                 purge_empty_chans();
1835         }
1836 }
1837
1838
1839
1840 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1841
1842 char* Passwd(userrec *user)
1843 {
1844         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1845         {
1846                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1847                 {
1848                         return i->pass;
1849                 }
1850         }
1851         return "";
1852 }
1853
1854 bool IsDenied(userrec *user)
1855 {
1856         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1857         {
1858                 if (match(user->host,i->host) && (i->type == CC_DENY))
1859                 {
1860                         return true;
1861                 }
1862         }
1863         return false;
1864 }
1865
1866
1867
1868
1869 /* sends out an error notice to all connected clients (not to be used
1870  * lightly!) */
1871
1872 void send_error(char *s)
1873 {
1874         log(DEBUG,"send_error: %s",s);
1875         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1876         {
1877                 if (isnick(i->second->nick))
1878                 {
1879                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1880                 }
1881                 else
1882                 {
1883                         // fix - unregistered connections receive ERROR, not NOTICE
1884                         Write(i->second->fd,"ERROR :%s",s);
1885                 }
1886         }
1887 }
1888
1889 void Error(int status)
1890 {
1891         signal (SIGALRM, SIG_IGN);
1892         signal (SIGPIPE, SIG_IGN);
1893         signal (SIGTERM, SIG_IGN);
1894         signal (SIGABRT, SIG_IGN);
1895         signal (SIGSEGV, SIG_IGN);
1896         signal (SIGURG, SIG_IGN);
1897         signal (SIGKILL, SIG_IGN);
1898         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1899         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1900         exit(status);
1901 }
1902
1903
1904 int main(int argc, char *argv[])
1905 {
1906         Start();
1907         srand(time(NULL));
1908         log(DEBUG,"*** InspIRCd starting up!");
1909         if (!FileExists(CONFIG_FILE))
1910         {
1911                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1912                 log(DEBUG,"main: no config");
1913                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1914                 Exit(ERROR);
1915         }
1916         if (argc > 1) {
1917                 if (!strcmp(argv[1],"-nofork")) {
1918                         nofork = true;
1919                 }
1920         }
1921         if (InspIRCd() == ERROR)
1922         {
1923                 log(DEBUG,"main: daemon function bailed");
1924                 printf("ERROR: could not initialise. Shutting down.\n");
1925                 Exit(ERROR);
1926         }
1927         Exit(TRUE);
1928         return 0;
1929 }
1930
1931 template<typename T> inline string ConvToStr(const T &in)
1932 {
1933         stringstream tmp;
1934         if (!(tmp << in)) return string();
1935         return tmp.str();
1936 }
1937
1938 /* re-allocates a nick in the user_hash after they change nicknames,
1939  * returns a pointer to the new user as it may have moved */
1940
1941 userrec* ReHashNick(char* Old, char* New)
1942 {
1943         user_hash::iterator newnick;
1944         user_hash::iterator oldnick = clientlist.find(Old);
1945
1946         log(DEBUG,"ReHashNick: %s %s",Old,New);
1947         
1948         if (!strcasecmp(Old,New))
1949         {
1950                 log(DEBUG,"old nick is new nick, skipping");
1951                 return oldnick->second;
1952         }
1953         
1954         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1955
1956         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1957
1958         clientlist[New] = new userrec();
1959         clientlist[New] = oldnick->second;
1960         /*delete oldnick->second; */
1961         clientlist.erase(oldnick);
1962
1963         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1964         
1965         return clientlist[New];
1966 }
1967
1968 /* adds or updates an entry in the whowas list */
1969 void AddWhoWas(userrec* u)
1970 {
1971         user_hash::iterator iter = whowas.find(u->nick);
1972         userrec *a = new userrec();
1973         strcpy(a->nick,u->nick);
1974         strcpy(a->ident,u->ident);
1975         strcpy(a->dhost,u->dhost);
1976         strcpy(a->host,u->host);
1977         strcpy(a->fullname,u->fullname);
1978         strcpy(a->server,u->server);
1979         a->signon = u->signon;
1980
1981         /* MAX_WHOWAS:   max number of /WHOWAS items
1982          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1983          *               can be replaced by a newer one
1984          */
1985         
1986         if (iter == whowas.end())
1987         {
1988                 if (whowas.size() == WHOWAS_MAX)
1989                 {
1990                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1991                         {
1992                                 // 3600 seconds in an hour ;)
1993                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
1994                                 {
1995                                         delete i->second;
1996                                         i->second = a;
1997                                         log(DEBUG,"added WHOWAS entry, purged an old record");
1998                                         return;
1999                                 }
2000                         }
2001                 }
2002                 else
2003                 {
2004                         log(DEBUG,"added fresh WHOWAS entry");
2005                         whowas[a->nick] = a;
2006                 }
2007         }
2008         else
2009         {
2010                 log(DEBUG,"updated WHOWAS entry");
2011                 delete iter->second;
2012                 iter->second = a;
2013         }
2014 }
2015
2016
2017 /* add a client connection to the sockets list */
2018 void AddClient(int socket, char* host, int port, bool iscached)
2019 {
2020         int i;
2021         int blocking = 1;
2022         char resolved[MAXBUF];
2023         string tempnick;
2024         char tn2[MAXBUF];
2025         user_hash::iterator iter;
2026
2027         tempnick = ConvToStr(socket) + "-unknown";
2028         sprintf(tn2,"%d-unknown",socket);
2029
2030         iter = clientlist.find(tempnick);
2031
2032         if (iter != clientlist.end()) return;
2033
2034         /*
2035          * It is OK to access the value here this way since we know
2036          * it exists, we just created it above.
2037          *
2038          * At NO other time should you access a value in a map or a
2039          * hash_map this way.
2040          */
2041         clientlist[tempnick] = new userrec();
2042
2043         NonBlocking(socket);
2044         log(DEBUG,"AddClient: %d %s %d",socket,host,port);
2045
2046         clientlist[tempnick]->fd = socket;
2047         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2048         strncpy(clientlist[tempnick]->host, host,160);
2049         strncpy(clientlist[tempnick]->dhost, host,160);
2050         strncpy(clientlist[tempnick]->server, ServerName,256);
2051         strncpy(clientlist[tempnick]->ident, "unknown",9);
2052         clientlist[tempnick]->registered = 0;
2053         clientlist[tempnick]->signon = time(NULL);
2054         clientlist[tempnick]->nping = time(NULL)+240;
2055         clientlist[tempnick]->lastping = 1;
2056         clientlist[tempnick]->port = port;
2057
2058         if (iscached)
2059         {
2060                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2061         }
2062         else
2063         {
2064                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2065         }
2066
2067         // set the registration timeout for this user
2068         unsigned long class_regtimeout = 90;
2069         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2070         {
2071                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2072                 {
2073                         class_regtimeout = (unsigned long)i->registration_timeout;
2074                         break;
2075                 }
2076         }
2077
2078         int class_flood = 0;
2079         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2080         {
2081                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2082                 {
2083                         class_flood = i->flood;
2084                         break;
2085                 }
2086         }
2087
2088         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2089         clientlist[tempnick]->flood = class_flood;
2090
2091         for (int i = 0; i < MAXCHANS; i++)
2092         {
2093                 clientlist[tempnick]->chans[i].channel = NULL;
2094                 clientlist[tempnick]->chans[i].uc_modes = 0;
2095         }
2096
2097         if (clientlist.size() == MAXCLIENTS)
2098                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2099 }
2100
2101
2102 int usercnt(void)
2103 {
2104         return clientlist.size();
2105 }
2106
2107
2108 int usercount_invisible(void)
2109 {
2110         int c = 0;
2111
2112         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2113         {
2114                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2115         }
2116         return c;
2117 }
2118
2119 int usercount_opers(void)
2120 {
2121         int c = 0;
2122
2123         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2124         {
2125                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2126         }
2127         return c;
2128 }
2129
2130 int usercount_unknown(void)
2131 {
2132         int c = 0;
2133
2134         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2135         {
2136                 if ((i->second->fd) && (i->second->registered != 7))
2137                         c++;
2138         }
2139         return c;
2140 }
2141
2142 long chancount(void)
2143 {
2144         return chanlist.size();
2145 }
2146
2147 long count_servs(void)
2148 {
2149         int c = 0;
2150         //for (int j = 0; j < 255; j++)
2151         //{
2152         //      if (servers[j] != NULL)
2153         //              c++;
2154         //}
2155         return c;
2156 }
2157
2158 long servercount(void)
2159 {
2160         return count_servs()+1;
2161 }
2162
2163 long local_count()
2164 {
2165         int c = 0;
2166         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2167         {
2168                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2169         }
2170         return c;
2171 }
2172
2173
2174 void ShowMOTD(userrec *user)
2175 {
2176         if (!MOTD.size())
2177         {
2178                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2179                 return;
2180         }
2181         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2182         for (int i = 0; i != MOTD.size(); i++)
2183         {
2184                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2185         }
2186         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2187 }
2188
2189 void ShowRULES(userrec *user)
2190 {
2191         if (!RULES.size())
2192         {
2193                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2194                 return;
2195         }
2196         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2197         for (int i = 0; i != RULES.size(); i++)
2198         {
2199                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2200         }
2201         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2202 }
2203
2204 /* shows the message of the day, and any other on-logon stuff */
2205 void ConnectUser(userrec *user)
2206 {
2207         user->registered = 7;
2208         user->idle_lastmsg = time(NULL);
2209         log(DEBUG,"ConnectUser: %s",user->nick);
2210
2211         if (strcmp(Passwd(user),"") && (!user->haspassed))
2212         {
2213                 kill_link(user,"Invalid password");
2214                 return;
2215         }
2216         if (IsDenied(user))
2217         {
2218                 kill_link(user,"Unauthorised connection");
2219                 return;
2220         }
2221
2222         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2223         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2224         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2225         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2226         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2227         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);
2228         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);
2229         ShowMOTD(user);
2230         FOREACH_MOD OnUserConnect(user);
2231         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2232         
2233         char buffer[MAXBUF];
2234         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);
2235         NetSendToAll(buffer);
2236 }
2237
2238 void handle_version(char **parameters, int pcnt, userrec *user)
2239 {
2240         char Revision[] = "$Revision$";
2241
2242         char *s1 = Revision;
2243         char *savept;
2244         char *v1 = strtok_r(s1," ",&savept);
2245         s1 = savept;
2246         char *v2 = strtok_r(s1," ",&savept);
2247         s1 = savept;
2248         
2249         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2250 }
2251
2252
2253 // calls a handler function for a command
2254
2255 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2256 {
2257                 for (int i = 0; i < cmdlist.size(); i++)
2258                 {
2259                         if (!strcasecmp(cmdlist[i].command,commandname))
2260                         {
2261                                 if (cmdlist[i].handler_function)
2262                                 {
2263                                         if (pcnt>=cmdlist[i].min_params)
2264                                         {
2265                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2266                                                 {
2267                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2268                                                 }
2269                                         }
2270                                 }
2271                         }
2272                 }
2273 }
2274
2275 void DoSplitEveryone()
2276 {
2277         bool go_again = true;
2278         while (go_again)
2279         {
2280                 go_again = false;
2281                 for (int i = 0; i < 32; i++)
2282                 {
2283                         if (me[i] != NULL)
2284                         {
2285                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2286                                 {
2287                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2288                                         {
2289                                                 j->routes.clear();
2290                                                 j->CloseConnection();
2291                                                 me[i]->connectors.erase(j);
2292                                                 go_again = true;
2293                                                 break;
2294                                         }
2295                                 }
2296                         }
2297                 }
2298         }
2299         log(DEBUG,"Removed server. Will remove clients...");
2300         // iterate through the userlist and remove all users on this server.
2301         // because we're dealing with a mesh, we dont have to deal with anything
2302         // "down-route" from this server (nice huh)
2303         go_again = true;
2304         char reason[MAXBUF];
2305         while (go_again)
2306         {
2307                 go_again = false;
2308                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2309                 {
2310                         if (strcasecmp(u->second->server,ServerName))
2311                         {
2312                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2313                                 kill_link(u->second,reason);
2314                                 go_again = true;
2315                                 break;
2316                         }
2317                 }
2318         }
2319 }
2320
2321
2322
2323 char islast(const char* s)
2324 {
2325         char c = '`';
2326         for (int j = 0; j < 32; j++)
2327         {
2328                 if (me[j] != NULL)
2329                 {
2330                         for (int k = 0; k < me[j]->connectors.size(); k++)
2331                         {
2332                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2333                                 {
2334                                         c = '|';
2335                                 }
2336                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2337                                 {
2338                                         c = '`';
2339                                 }
2340                         }
2341                 }
2342         }
2343         return c;
2344 }
2345
2346 long map_count(const char* s)
2347 {
2348         int c = 0;
2349         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2350         {
2351                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2352         }
2353         return c;
2354 }
2355
2356
2357 void force_nickchange(userrec* user,const char* newnick)
2358 {
2359         char nick[MAXBUF];
2360         int MOD_RESULT = 0;
2361         
2362         strcpy(nick,"");
2363
2364         FOREACH_RESULT(OnUserPreNick(user,newnick));
2365         if (MOD_RESULT) {
2366                 kill_link(user,"Nickname collision");
2367                 return;
2368         }
2369         
2370         if (user)
2371         {
2372                 if (newnick)
2373                 {
2374                         strncpy(nick,newnick,MAXBUF);
2375                 }
2376                 if (user->registered == 7)
2377                 {
2378                         char* pars[1];
2379                         pars[0] = nick;
2380                         handle_nick(pars,1,user);
2381                 }
2382         }
2383 }
2384                                 
2385
2386 int process_parameters(char **command_p,char *parameters)
2387 {
2388         int i = 0;
2389         int j = 0;
2390         int q = 0;
2391         q = strlen(parameters);
2392         if (!q)
2393         {
2394                 /* no parameters, command_p invalid! */
2395                 return 0;
2396         }
2397         if (parameters[0] == ':')
2398         {
2399                 command_p[0] = parameters+1;
2400                 return 1;
2401         }
2402         if (q)
2403         {
2404                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2405                 {
2406                         /* only one parameter */
2407                         command_p[0] = parameters;
2408                         if (parameters[0] == ':')
2409                         {
2410                                 if (strchr(parameters,' ') != NULL)
2411                                 {
2412                                         command_p[0]++;
2413                                 }
2414                         }
2415                         return 1;
2416                 }
2417         }
2418         command_p[j++] = parameters;
2419         for (int i = 0; i <= q; i++)
2420         {
2421                 if (parameters[i] == ' ')
2422                 {
2423                         command_p[j++] = parameters+i+1;
2424                         parameters[i] = '\0';
2425                         if (command_p[j-1][0] == ':')
2426                         {
2427                                 *command_p[j-1]++; /* remove dodgy ":" */
2428                                 break;
2429                                 /* parameter like this marks end of the sequence */
2430                         }
2431                 }
2432         }
2433         return j; /* returns total number of items in the list */
2434 }
2435
2436 void process_command(userrec *user, char* cmd)
2437 {
2438         char *parameters;
2439         char *command;
2440         char *command_p[127];
2441         char p[MAXBUF], temp[MAXBUF];
2442         int i, j, items, cmd_found;
2443
2444         for (int i = 0; i < 127; i++)
2445                 command_p[i] = NULL;
2446
2447         if (!user)
2448         {
2449                 return;
2450         }
2451         if (!cmd)
2452         {
2453                 return;
2454         }
2455         if (!strcmp(cmd,""))
2456         {
2457                 return;
2458         }
2459         
2460         int total_params = 0;
2461         if (strlen(cmd)>2)
2462         {
2463                 for (int q = 0; q < strlen(cmd)-1; q++)
2464                 {
2465                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2466                         {
2467                                 total_params++;
2468                                 // found a 'trailing', we dont count them after this.
2469                                 break;
2470                         }
2471                         if (cmd[q] == ' ')
2472                                 total_params++;
2473                 }
2474         }
2475         
2476         // another phidjit bug...
2477         if (total_params > 126)
2478         {
2479                 kill_link(user,"Protocol violation (1)");
2480                 return;
2481         }
2482         
2483         strcpy(temp,cmd);
2484
2485         std::string tmp = cmd;
2486         for (int i = 0; i <= MODCOUNT; i++)
2487         {
2488                 std::string oldtmp = tmp;
2489                 modules[i]->OnServerRaw(tmp,true);
2490                 if (oldtmp != tmp)
2491                 {
2492                         log(DEBUG,"A Module changed the input string!");
2493                         log(DEBUG,"New string: %s",tmp.c_str());
2494                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2495                         break;
2496                 }
2497         }
2498         strncpy(cmd,tmp.c_str(),MAXBUF);
2499         strcpy(temp,cmd);
2500
2501         if (!strchr(cmd,' '))
2502         {
2503                 /* no parameters, lets skip the formalities and not chop up
2504                  * the string */
2505                 log(DEBUG,"About to preprocess command with no params");
2506                 items = 0;
2507                 command_p[0] = NULL;
2508                 parameters = NULL;
2509                 for (int i = 0; i <= strlen(cmd); i++)
2510                 {
2511                         cmd[i] = toupper(cmd[i]);
2512                 }
2513                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2514                 command = cmd;
2515         }
2516         else
2517         {
2518                 strcpy(cmd,"");
2519                 j = 0;
2520                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2521                 for (int i = 0; i < strlen(temp); i++)
2522                 {
2523                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2524                         {
2525                                 cmd[j++] = temp[i];
2526                                 cmd[j] = 0;
2527                         }
2528                 }
2529                 /* split the full string into a command plus parameters */
2530                 parameters = p;
2531                 strcpy(p," ");
2532                 command = cmd;
2533                 if (strchr(cmd,' '))
2534                 {
2535                         for (int i = 0; i <= strlen(cmd); i++)
2536                         {
2537                                 /* capitalise the command ONLY, leave params intact */
2538                                 cmd[i] = toupper(cmd[i]);
2539                                 /* are we nearly there yet?! :P */
2540                                 if (cmd[i] == ' ')
2541                                 {
2542                                         command = cmd;
2543                                         parameters = cmd+i+1;
2544                                         cmd[i] = '\0';
2545                                         break;
2546                                 }
2547                         }
2548                 }
2549                 else
2550                 {
2551                         for (int i = 0; i <= strlen(cmd); i++)
2552                         {
2553                                 cmd[i] = toupper(cmd[i]);
2554                         }
2555                 }
2556
2557         }
2558         cmd_found = 0;
2559         
2560         if (strlen(command)>MAXCOMMAND)
2561         {
2562                 kill_link(user,"Protocol violation (2)");
2563                 return;
2564         }
2565         
2566         for (int x = 0; x < strlen(command); x++)
2567         {
2568                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2569                 {
2570                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2571                         {
2572                                 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2573                                 {
2574                                         kill_link(user,"Protocol violation (3)");
2575                                         return;
2576                                 }
2577                         }
2578                 }
2579         }
2580
2581         for (int i = 0; i != cmdlist.size(); i++)
2582         {
2583                 if (strcmp(cmdlist[i].command,""))
2584                 {
2585                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2586                         {
2587                                 log(DEBUG,"Found matching command");
2588
2589                                 if (parameters)
2590                                 {
2591                                         if (strcmp(parameters,""))
2592                                         {
2593                                                 items = process_parameters(command_p,parameters);
2594                                         }
2595                                         else
2596                                         {
2597                                                 items = 0;
2598                                                 command_p[0] = NULL;
2599                                         }
2600                                 }
2601                                 else
2602                                 {
2603                                         items = 0;
2604                                         command_p[0] = NULL;
2605                                 }
2606                                 
2607                                 if (user)
2608                                 {
2609                                         log(DEBUG,"Processing command");
2610                                         
2611                                         /* activity resets the ping pending timer */
2612                                         user->nping = time(NULL) + 120;
2613                                         if ((items) < cmdlist[i].min_params)
2614                                         {
2615                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2616                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2617                                                 return;
2618                                         }
2619                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2620                                         {
2621                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2622                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2623                                                 cmd_found = 1;
2624                                                 return;
2625                                         }
2626                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2627                                          * deny command! */
2628                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2629                                         {
2630                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2631                                                 {
2632                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2633                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2634                                                         return;
2635                                                 }
2636                                         }
2637                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2638                                         {
2639                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2640                                                 if (cmdlist[i].handler_function)
2641                                                 {
2642                                                         /* ikky /stats counters */
2643                                                         if (temp)
2644                                                         {
2645                                                                 if (user)
2646                                                                 {
2647                                                                         user->bytes_in += strlen(temp);
2648                                                                         user->cmds_in++;
2649                                                                 }
2650                                                                 cmdlist[i].use_count++;
2651                                                                 cmdlist[i].total_bytes+=strlen(temp);
2652                                                         }
2653
2654                                                         /* WARNING: nothing may come after the
2655                                                          * command handler call, as the handler
2656                                                          * may free the user structure! */
2657
2658                                                         cmdlist[i].handler_function(command_p,items,user);
2659                                                 }
2660                                                 return;
2661                                         }
2662                                         else
2663                                         {
2664                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2665                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2666                                                 return;
2667                                         }
2668                                 }
2669                                 cmd_found = 1;
2670                         }
2671                 }
2672         }
2673         if ((!cmd_found) && (user))
2674         {
2675                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2676                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2677         }
2678 }
2679
2680
2681 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2682 {
2683         command_t comm;
2684         /* create the command and push it onto the table */     
2685         strcpy(comm.command,cmd);
2686         comm.handler_function = f;
2687         comm.flags_needed = flags;
2688         comm.min_params = minparams;
2689         comm.use_count = 0;
2690         comm.total_bytes = 0;
2691         cmdlist.push_back(comm);
2692         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2693 }
2694
2695 void SetupCommandTable(void)
2696 {
2697         createcommand("USER",handle_user,0,4);
2698         createcommand("NICK",handle_nick,0,1);
2699         createcommand("QUIT",handle_quit,0,0);
2700         createcommand("VERSION",handle_version,0,0);
2701         createcommand("PING",handle_ping,0,1);
2702         createcommand("PONG",handle_pong,0,1);
2703         createcommand("ADMIN",handle_admin,0,0);
2704         createcommand("PRIVMSG",handle_privmsg,0,2);
2705         createcommand("INFO",handle_info,0,0);
2706         createcommand("TIME",handle_time,0,0);
2707         createcommand("WHOIS",handle_whois,0,1);
2708         createcommand("WALLOPS",handle_wallops,'o',1);
2709         createcommand("NOTICE",handle_notice,0,2);
2710         createcommand("JOIN",handle_join,0,1);
2711         createcommand("NAMES",handle_names,0,1);
2712         createcommand("PART",handle_part,0,1);
2713         createcommand("KICK",handle_kick,0,2);
2714         createcommand("MODE",handle_mode,0,1);
2715         createcommand("TOPIC",handle_topic,0,1);
2716         createcommand("WHO",handle_who,0,1);
2717         createcommand("MOTD",handle_motd,0,0);
2718         createcommand("RULES",handle_rules,0,0);
2719         createcommand("OPER",handle_oper,0,2);
2720         createcommand("LIST",handle_list,0,0);
2721         createcommand("DIE",handle_die,'o',1);
2722         createcommand("RESTART",handle_restart,'o',1);
2723         createcommand("KILL",handle_kill,'o',2);
2724         createcommand("REHASH",handle_rehash,'o',0);
2725         createcommand("LUSERS",handle_lusers,0,0);
2726         createcommand("STATS",handle_stats,0,1);
2727         createcommand("USERHOST",handle_userhost,0,1);
2728         createcommand("AWAY",handle_away,0,0);
2729         createcommand("ISON",handle_ison,0,0);
2730         createcommand("SUMMON",handle_summon,0,0);
2731         createcommand("USERS",handle_users,0,0);
2732         createcommand("INVITE",handle_invite,0,2);
2733         createcommand("PASS",handle_pass,0,1);
2734         createcommand("TRACE",handle_trace,'o',0);
2735         createcommand("WHOWAS",handle_whowas,0,1);
2736         createcommand("CONNECT",handle_connect,'o',1);
2737         createcommand("SQUIT",handle_squit,'o',0);
2738         createcommand("MODULES",handle_modules,'o',0);
2739         createcommand("LINKS",handle_links,0,0);
2740         createcommand("MAP",handle_map,0,0);
2741 }
2742
2743 void process_buffer(const char* cmdbuf,userrec *user)
2744 {
2745         if (!user)
2746         {
2747                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2748                 return;
2749         }
2750         char cmd[MAXBUF];
2751         int i;
2752         if (!cmdbuf)
2753         {
2754                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2755                 return;
2756         }
2757         if (!strcmp(cmdbuf,""))
2758         {
2759                 return;
2760         }
2761         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2762
2763         strncpy(cmd,cmdbuf,MAXBUF);
2764         if (!strcmp(cmd,""))
2765         {
2766                 return;
2767         }
2768         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2769         {
2770                 cmd[strlen(cmd)-1] = '\0';
2771         }
2772         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2773         {
2774                 cmd[strlen(cmd)-1] = '\0';
2775         }
2776
2777         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2778         {
2779                 cmd[strlen(cmd)-1] = '\0';
2780         }
2781
2782         if (!strcmp(cmd,""))
2783         {
2784                 return;
2785         }
2786         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2787         tidystring(cmd);
2788         if ((user) && (cmd))
2789         {
2790                 process_command(user,cmd);
2791         }
2792 }
2793
2794 void DoSync(serverrec* serv, char* tcp_host)
2795 {
2796         char data[MAXBUF];
2797         log(DEBUG,"Sending sync");
2798         // send start of sync marker: Y <timestamp>
2799         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2800         // except the ones its receiving it from.
2801         snprintf(data,MAXBUF,"Y %d",time(NULL));
2802         serv->SendPacket(data,tcp_host);
2803         // send users and channels
2804         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2805         {
2806                 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);
2807                 serv->SendPacket(data,tcp_host);
2808                 if (strcmp(chlist(u->second),""))
2809                 {
2810                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2811                         serv->SendPacket(data,tcp_host);
2812                 }
2813         }
2814         // send channel modes, topics etc...
2815         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2816         {
2817                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2818                 serv->SendPacket(data,tcp_host);
2819                 if (strcmp(c->second->topic,""))
2820                 {
2821                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2822                         serv->SendPacket(data,tcp_host);
2823                 }
2824                 // send current banlist
2825                 
2826                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2827                 {
2828                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2829                         serv->SendPacket(data,tcp_host);
2830                 }
2831         }
2832         snprintf(data,MAXBUF,"F %d",time(NULL));
2833         serv->SendPacket(data,tcp_host);
2834         log(DEBUG,"Sent sync");
2835         // ircd sends its serverlist after the end of sync here
2836 }
2837
2838
2839 void NetSendMyRoutingTable()
2840 {
2841         // send out a line saying what is reachable to us.
2842         // E.g. if A is linked to B C and D, send out:
2843         // $ A B C D
2844         // if its only linked to B and D send out:
2845         // $ A B D
2846         // if it has no links, dont even send out the line at all.
2847         char buffer[MAXBUF];
2848         sprintf(buffer,"$ %s",ServerName);
2849         bool sendit = false;
2850         for (int i = 0; i < 32; i++)
2851         {
2852                 if (me[i] != NULL)
2853                 {
2854                         for (int j = 0; j < me[i]->connectors.size(); j++)
2855                         {
2856                                 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2857                                 {
2858                                         strncat(buffer," ",MAXBUF);
2859                                         strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2860                                         sendit = true;
2861                                 }
2862                         }
2863                 }
2864         }
2865         if (sendit)
2866                 NetSendToAll(buffer);
2867 }
2868
2869
2870 void DoSplit(const char* params)
2871 {
2872         bool go_again = true;
2873         while (go_again)
2874         {
2875                 go_again = false;
2876                 for (int i = 0; i < 32; i++)
2877                 {
2878                         if (me[i] != NULL)
2879                         {
2880                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2881                                 {
2882                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2883                                         {
2884                                                 j->routes.clear();
2885                                                 j->CloseConnection();
2886                                                 me[i]->connectors.erase(j);
2887                                                 go_again = true;
2888                                                 break;
2889                                         }
2890                                 }
2891                         }
2892                 }
2893         }
2894         log(DEBUG,"Removed server. Will remove clients...");
2895         // iterate through the userlist and remove all users on this server.
2896         // because we're dealing with a mesh, we dont have to deal with anything
2897         // "down-route" from this server (nice huh)
2898         go_again = true;
2899         char reason[MAXBUF];
2900         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2901         while (go_again)
2902         {
2903                 go_again = false;
2904                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2905                 {
2906                         if (!strcasecmp(u->second->server,params))
2907                         {
2908                                 kill_link(u->second,reason);
2909                                 go_again = true;
2910                                 break;
2911                         }
2912                 }
2913         }
2914 }
2915
2916 // removes a server. Will NOT remove its users!
2917
2918 void RemoveServer(const char* name)
2919 {
2920         bool go_again = true;
2921         while (go_again)
2922         {
2923                 go_again = false;
2924                 for (int i = 0; i < 32; i++)
2925                 {
2926                         if (me[i] != NULL)
2927                         {
2928                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2929                                 {
2930                                         if (!strcasecmp(j->GetServerName().c_str(),name))
2931                                         {
2932                                                 j->routes.clear();
2933                                                 j->CloseConnection();
2934                                                 me[i]->connectors.erase(j);
2935                                                 go_again = true;
2936                                                 break;
2937                                         }
2938                                 }
2939                         }
2940                 }
2941         }
2942 }
2943
2944
2945 int reap_counter = 0;
2946
2947 int InspIRCd(void)
2948 {
2949         struct sockaddr_in client, server;
2950         char addrs[MAXBUF][255];
2951         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
2952         socklen_t length;
2953         int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
2954         int selectResult = 0, selectResult2 = 0;
2955         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2956         char resolvedHost[MAXBUF];
2957         fd_set selectFds;
2958         struct timeval tv;
2959
2960         log_file = fopen("ircd.log","a+");
2961         if (!log_file)
2962         {
2963                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
2964                 Exit(ERROR);
2965         }
2966
2967         log(DEBUG,"InspIRCd: startup: begin");
2968         log(DEBUG,"$Id$");
2969         if (geteuid() == 0)
2970         {
2971                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2972                 Exit(ERROR);
2973                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
2974         }
2975         SetupCommandTable();
2976         log(DEBUG,"InspIRCd: startup: default command table set up");
2977         
2978         ReadConfig();
2979         if (strcmp(DieValue,"")) 
2980         { 
2981                 printf("WARNING: %s\n\n",DieValue);
2982                 exit(0); 
2983         }  
2984         log(DEBUG,"InspIRCd: startup: read config");
2985           
2986         int count2 = 0, count3 = 0;
2987
2988         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2989         {
2990                 ConfValue("bind","port",count,configToken,&config_f);
2991                 ConfValue("bind","address",count,Addr,&config_f);
2992                 ConfValue("bind","type",count,Type,&config_f);
2993                 if (!strcmp(Type,"servers"))
2994                 {
2995                         char Default[MAXBUF];
2996                         strcpy(Default,"no");
2997                         ConfValue("bind","default",count,Default,&config_f);
2998                         if (strchr(Default,'y'))
2999                         {
3000                                 defaultRoute = count3;
3001                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3002                         }
3003                         me[count3] = new serverrec(ServerName,100L,false);
3004                         me[count3]->CreateListener(Addr,atoi(configToken));
3005                         count3++;
3006                 }
3007                 else
3008                 {
3009                         ports[count2] = atoi(configToken);
3010                         strcpy(addrs[count2],Addr);
3011                         count2++;
3012                 }
3013                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3014         }
3015         portCount = count2;
3016         UDPportCount = count3;
3017           
3018         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3019         
3020         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3021         
3022         printf("\n");
3023         
3024         /* BugFix By Craig! :p */
3025         count = 0;
3026         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3027         {
3028                 char modfile[MAXBUF];
3029                 ConfValue("module","name",count2,configToken,&config_f);
3030                 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3031                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3032                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3033                 /* If The File Doesnt exist, Trying to load it
3034                  * Will Segfault the IRCd.. So, check to see if
3035                  * it Exists, Before Proceeding. */
3036                 if (FileExists(modfile))
3037                 {
3038                         factory[count] = new ircd_module(modfile);
3039                         if (factory[count]->LastError())
3040                         {
3041                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3042                                 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3043                                 Exit(ERROR);
3044                         }
3045                         if (factory[count]->factory)
3046                         {
3047                                 modules[count] = factory[count]->factory->CreateModule();
3048                                 /* save the module and the module's classfactory, if
3049                                  * this isnt done, random crashes can occur :/ */
3050                                 module_names.push_back(modfile);        
3051                         }
3052                         else
3053                         {
3054                                 log(DEBUG,"Unable to load %s",modfile);
3055                                 sprintf("Unable to load %s\nExiting...\n",modfile);
3056                                 Exit(ERROR);
3057                         }
3058                         /* Increase the Count */
3059                         count++;
3060                 }
3061                 else
3062                 {
3063                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3064                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3065                 }
3066         }
3067         MODCOUNT = count - 1;
3068         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3069         
3070         printf("\nInspIRCd is now running!\n");
3071         
3072         startup_time = time(NULL);
3073           
3074         if (nofork)
3075         {
3076                 log(VERBOSE,"Not forking as -nofork was specified");
3077         }
3078         else
3079         {
3080                 if (DaemonSeed() == ERROR)
3081                 {
3082                         log(DEBUG,"InspIRCd: startup: can't daemonise");
3083                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3084                         Exit(ERROR);
3085                 }
3086         }
3087           
3088           
3089         /* setup select call */
3090         FD_ZERO(&selectFds);
3091         log(DEBUG,"InspIRCd: startup: zero selects");
3092         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3093         
3094         for (count = 0; count < portCount; count++)
3095         {
3096                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3097                 {
3098                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3099                         return(ERROR);
3100                 }
3101                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3102                 {
3103                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3104                 }
3105                 else    /* well we at least bound to one socket so we'll continue */
3106                 {
3107                         boundPortCount++;
3108                 }
3109         }
3110         
3111         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3112           
3113         /* if we didn't bind to anything then abort */
3114         if (boundPortCount == 0)
3115         {
3116                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3117                 return (ERROR);
3118         }
3119         
3120
3121         length = sizeof (client);
3122         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3123           
3124         /* main loop, this never returns */
3125         for (;;)
3126         {
3127 #ifdef _POSIX_PRIORITY_SCHEDULING
3128                 sched_yield();
3129 #endif
3130
3131                 fd_set sfd;
3132                 timeval tval;
3133                 FD_ZERO(&sfd);
3134
3135                 user_hash::iterator count2 = clientlist.begin();
3136
3137                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3138                 // them in a list, then reap the list every second or so.
3139                 if (reap_counter>300)
3140                 {
3141                         if (fd_reap.size() > 0)
3142                         {
3143                                 for( int n = 0; n < fd_reap.size(); n++)
3144                                 {
3145                                         Blocking(fd_reap[n]);
3146                                         close(fd_reap[n]);
3147                                         NonBlocking(fd_reap[n]);
3148                                 }
3149                         }
3150                         fd_reap.clear();
3151                         reap_counter=0;
3152                 }
3153                 reap_counter++;
3154
3155                 fd_set serverfds;
3156                 FD_ZERO(&serverfds);
3157                 timeval tvs;
3158                 
3159                 for (int x = 0; x != UDPportCount; x++)
3160                 {
3161                         FD_SET(me[x]->fd, &serverfds);
3162                 }
3163                 
3164                 tvs.tv_usec = 0;                
3165                 tvs.tv_sec = 0;
3166                 
3167                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3168                 if (servresult > 0)
3169                 {
3170                         for (int x = 0; x != UDPportCount; x++)
3171                         {
3172                                 if (FD_ISSET (me[x]->fd, &serverfds))
3173                                 {
3174                                         char remotehost[MAXBUF],resolved[MAXBUF];
3175                                         length = sizeof (client);
3176                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3177                                         strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3178                                         if(CleanAndResolve(resolved, remotehost) != TRUE)
3179                                         {
3180                                                 strncpy(resolved,remotehost,MAXBUF);
3181                                         }
3182                                         // add to this connections ircd_connector vector
3183                                         // *FIX* - we need the LOCAL port not the remote port in &client!
3184                                         me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3185                                 }
3186                         }
3187                 }
3188      
3189                 for (int x = 0; x < UDPportCount; x++)
3190                 {
3191                         std::deque<std::string> msgs;
3192                         msgs.clear();
3193                         if (me[x]->RecvPacket(msgs, tcp_host))
3194                         {
3195                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
3196                                 {
3197                                         char udp_msg[MAXBUF];
3198                                         strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3199                                         if (strlen(udp_msg)<1)
3200                                         {
3201                                                 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3202                                                 break;
3203                                         }
3204                                         // during a netburst, send all data to all other linked servers
3205                                         if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3206                                         {
3207                                                 if (is_uline(tcp_host))
3208                                                 {
3209                                                         if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3210                                                         {
3211                                                                 NetSendToAllExcept(tcp_host,udp_msg);
3212                                                         }
3213                                                 }
3214                                                 else
3215                                                         NetSendToAllExcept(tcp_host,udp_msg);
3216                                         }
3217                                         FOREACH_MOD OnPacketReceive(udp_msg);
3218                                         handle_link_packet(udp_msg, tcp_host, me[x]);
3219                                 }
3220                                 goto label;
3221                         }
3222                 }
3223         
3224
3225         while (count2 != clientlist.end())
3226         {
3227                 char data[10240];
3228                 tval.tv_usec = tval.tv_sec = 0;
3229                 FD_ZERO(&sfd);
3230                 int total_in_this_set = 0;
3231
3232                 user_hash::iterator xcount = count2;
3233                 user_hash::iterator endingiter = count2;
3234
3235                 if (!count2->second) break;
3236                 
3237                 if (count2->second)
3238                 if (count2->second->fd != 0)
3239                 {
3240                         // assemble up to 64 sockets into an fd_set
3241                         // to implement a pooling mechanism.
3242                         //
3243                         // This should be up to 64x faster than the
3244                         // old implementation.
3245                         while (total_in_this_set < 64)
3246                         {
3247                                 if (count2 != clientlist.end())
3248                                 {
3249                                         // we don't check the state of remote users.
3250                                         if (count2->second->fd > 0)
3251                                         {
3252                                                 FD_SET (count2->second->fd, &sfd);
3253
3254                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3255                                                 // their connection class.
3256                                                 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
3257                                                 {
3258                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3259                                                         kill_link(count2->second,"Registration timeout");
3260                                                         goto label;
3261                                                 }
3262                                                 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3263                                                 {
3264                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
3265                                                         {
3266                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3267                                                                 kill_link(count2->second,"Ping timeout");
3268                                                                 goto label;
3269                                                         }
3270                                                         Write(count2->second->fd,"PING :%s",ServerName);
3271                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3272                                                         count2->second->lastping = 0;
3273                                                         count2->second->nping = time(NULL)+120;
3274                                                 }
3275                                         }
3276                                         count2++;
3277                                         total_in_this_set++;
3278                                 }
3279                                 else break;
3280                         }
3281    
3282                         endingiter = count2;
3283                         count2 = xcount; // roll back to where we were
3284         
3285                         int v = 0;
3286
3287                         tval.tv_usec = 0;
3288                         tval.tv_sec = 0;
3289                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3290                         
3291                         // now loop through all of the items in this pool if any are waiting
3292                         //if (selectResult2 > 0)
3293                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3294                         {
3295
3296 #ifdef _POSIX_PRIORITY_SCHEDULING
3297                                 sched_yield();
3298 #endif
3299
3300                                 result = EAGAIN;
3301                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3302                                 {
3303                                         log(DEBUG,"Reading fd %d",count2a->second->fd);
3304                                         memset(data, 0, 10240);
3305                                         result = read(count2a->second->fd, data, 10240);
3306                                         
3307                                         if (result)
3308                                         {
3309                                                 if (result > 0)
3310                                                         log(DEBUG,"Read %d characters from socket",result);
3311                                                 userrec* current = count2a->second;
3312                                                 int currfd = current->fd;
3313                                                 char* l = strtok(data,"\n");
3314                                                 int floodlines = 0;
3315                                                 while (l)
3316                                                 {
3317                                                         floodlines++;
3318                                                         if ((floodlines > current->flood) && (current->flood != 0))
3319                                                         {
3320                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3321                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3322                                                                 kill_link(current,"Excess flood");
3323                                                                 goto label;
3324                                                         }
3325                                                         char sanitized[NetBufferSize];
3326                                                         memset(sanitized, 0, NetBufferSize);
3327                                                         int ptt = 0;
3328                                                         for (int pt = 0; pt < strlen(l); pt++)
3329                                                         {
3330                                                                 if (l[pt] != '\r')
3331                                                                 {
3332                                                                         sanitized[ptt++] = l[pt];
3333                                                                 }
3334                                                         }
3335                                                         sanitized[ptt] = '\0';
3336                                                         if (strlen(sanitized))
3337                                                         {
3338
3339
3340                                                                 // we're gonna re-scan to check if the nick is gone, after every
3341                                                                 // command - if it has, we're gonna bail
3342                                                                 bool find_again = false;
3343                                                                 process_buffer(sanitized,current);
3344         
3345                                                                 // look for the user's record in case it's changed
3346                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3347                                                                 {
3348                                                                         if (c2->second->fd == currfd)
3349                                                                         {
3350                                                                                 // found again, update pointer
3351                                                                                 current == c2->second;
3352                                                                                 find_again = true;
3353                                                                                 break;
3354                                                                         }
3355                                                                 }
3356                                                                 if (!find_again)
3357                                                                         goto label;
3358
3359                                                         }
3360                                                         l = strtok(NULL,"\n");
3361                                                 }
3362                                                 goto label;
3363                                         }
3364
3365                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3366                                         {
3367                                                 log(DEBUG,"killing: %s",count2a->second->nick);
3368                                                 kill_link(count2a->second,strerror(errno));
3369                                                 goto label;
3370                                         }
3371                                 }
3372                                 // result EAGAIN means nothing read
3373                                 if (result == EAGAIN)
3374                                 {
3375                                 }
3376                                 else
3377                                 if (result == 0)
3378                                 {
3379                                         if (count2->second)
3380                                         {
3381                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3382                                                 kill_link(count2a->second,"Client exited");
3383                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3384                                                 log(DEBUG,"Bailing from client exit");
3385                                                 goto label;
3386                                         }
3387                                 }
3388                                 else if (result > 0)
3389                                 {
3390                                 }
3391                         }
3392                 }
3393                 for (int q = 0; q < total_in_this_set; q++)
3394                 {
3395                         // there is no iterator += operator :(
3396                         //if (count2 != clientlist.end())
3397                         //{
3398                                 count2++;
3399                         //}
3400                 }
3401         }
3402         
3403         // set up select call
3404         for (count = 0; count < boundPortCount; count++)
3405         {
3406                 FD_SET (openSockfd[count], &selectFds);
3407         }
3408
3409         tv.tv_usec = 1;
3410         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3411
3412         /* select is reporting a waiting socket. Poll them all to find out which */
3413         if (selectResult > 0)
3414         {
3415                 char target[MAXBUF], resolved[MAXBUF];
3416                 for (count = 0; count < boundPortCount; count++)                
3417                 {
3418                         if (FD_ISSET (openSockfd[count], &selectFds))
3419                         {
3420                                 length = sizeof (client);
3421                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3422                               
3423                                 address_cache::iterator iter = IP.find(client.sin_addr);
3424                                 bool iscached = false;
3425                                 if (iter == IP.end())
3426                                 {
3427                                         /* ip isn't in cache, add it */
3428                                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3429                                         if(CleanAndResolve(resolved, target) != TRUE)
3430                                         {
3431                                                 strncpy(resolved,target,MAXBUF);
3432                                         }
3433                                         /* hostname now in 'target' */
3434                                         IP[client.sin_addr] = new string(resolved);
3435                                         /* hostname in cache */
3436                                 }
3437                                 else
3438                                 {
3439                                         /* found ip (cached) */
3440                                         strncpy(resolved, iter->second->c_str(), MAXBUF);
3441                                         iscached = true;
3442                                 }
3443                         
3444                                 if (incomingSockfd < 0)
3445                                 {
3446                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3447                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3448                                 }
3449                                 else
3450                                 {
3451                                         AddClient(incomingSockfd, resolved, ports[count], iscached);
3452                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3453                                 }
3454                                 goto label;
3455                         }
3456                 }
3457         }
3458         label:
3459         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3460 }
3461 /* not reached */
3462 close (incomingSockfd);
3463 }
3464