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