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