]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
989e3e6b70135ec41e334cd8eb4d620b4d6702c3
[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::vector<userrec*> pending_connects;
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(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,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,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 }
1937
1938 void kill_link_silent(userrec *user,const char* r)
1939 {
1940         user_hash::iterator iter = clientlist.find(user->nick);
1941         
1942         char reason[MAXBUF];
1943         
1944         strncpy(reason,r,MAXBUF);
1945
1946         if (strlen(reason)>MAXQUIT)
1947         {
1948                 reason[MAXQUIT-1] = '\0';
1949         }
1950
1951         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1952         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1953         log(DEBUG,"closing fd %d",user->fd);
1954
1955         /* bugfix, cant close() a nonblocking socket (sux!) */
1956         if (user->registered == 7) {
1957                 FOREACH_MOD OnUserQuit(user);
1958                 WriteCommonExcept(user,"QUIT :%s",reason);
1959
1960                 // Q token must go to ALL servers!!!
1961                 char buffer[MAXBUF];
1962                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1963                 NetSendToAll(buffer);
1964         }
1965
1966         /* push the socket on a stack of sockets due to be closed at the next opportunity
1967          * 'Client exited' is an exception to this as it means the client side has already
1968          * closed the socket, we don't need to do it.
1969          */
1970         fd_reap.push_back(user->fd);
1971         
1972         bool do_purge = false;
1973         
1974         if (iter != clientlist.end())
1975         {
1976                 log(DEBUG,"deleting user hash value %d",iter->second);
1977                 if ((iter->second) && (user->registered == 7)) {
1978                         if (iter->second) delete iter->second;
1979                 }
1980                 clientlist.erase(iter);
1981         }
1982
1983         if (user->registered == 7) {
1984                 purge_empty_chans();
1985         }
1986 }
1987
1988
1989
1990 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1991
1992 char* Passwd(userrec *user)
1993 {
1994         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1995         {
1996                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1997                 {
1998                         return i->pass;
1999                 }
2000         }
2001         return "";
2002 }
2003
2004 bool IsDenied(userrec *user)
2005 {
2006         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2007         {
2008                 if (match(user->host,i->host) && (i->type == CC_DENY))
2009                 {
2010                         return true;
2011                 }
2012         }
2013         return false;
2014 }
2015
2016
2017
2018
2019 /* sends out an error notice to all connected clients (not to be used
2020  * lightly!) */
2021
2022 void send_error(char *s)
2023 {
2024         log(DEBUG,"send_error: %s",s);
2025         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2026         {
2027                 if (isnick(i->second->nick))
2028                 {
2029                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2030                 }
2031                 else
2032                 {
2033                         // fix - unregistered connections receive ERROR, not NOTICE
2034                         Write(i->second->fd,"ERROR :%s",s);
2035                 }
2036         }
2037 }
2038
2039 void Error(int status)
2040 {
2041         signal (SIGALRM, SIG_IGN);
2042         signal (SIGPIPE, SIG_IGN);
2043         signal (SIGTERM, SIG_IGN);
2044         signal (SIGABRT, SIG_IGN);
2045         signal (SIGSEGV, SIG_IGN);
2046         signal (SIGURG, SIG_IGN);
2047         signal (SIGKILL, SIG_IGN);
2048         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2049         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2050         exit(status);
2051 }
2052
2053
2054 int main(int argc, char **argv)
2055 {
2056         Start();
2057         srand(time(NULL));
2058         log(DEBUG,"*** InspIRCd starting up!");
2059         if (!FileExists(CONFIG_FILE))
2060         {
2061                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2062                 log(DEBUG,"main: no config");
2063                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2064                 Exit(ERROR);
2065         }
2066         if (argc > 1) {
2067                 for (int i = 1; i < argc; i++)
2068                 {
2069                         if (!strcmp(argv[i],"-nofork")) {
2070                                 nofork = true;
2071                         }
2072                         if (!strcmp(argv[i],"-wait")) {
2073                                 sleep(6);
2074                         }
2075                 }
2076         }
2077         strlcpy(MyExecutable,argv[0],MAXBUF);
2078         
2079         if (InspIRCd() == ERROR)
2080         {
2081                 log(DEBUG,"main: daemon function bailed");
2082                 printf("ERROR: could not initialise. Shutting down.\n");
2083                 Exit(ERROR);
2084         }
2085         Exit(TRUE);
2086         return 0;
2087 }
2088
2089 template<typename T> inline string ConvToStr(const T &in)
2090 {
2091         stringstream tmp;
2092         if (!(tmp << in)) return string();
2093         return tmp.str();
2094 }
2095
2096 /* re-allocates a nick in the user_hash after they change nicknames,
2097  * returns a pointer to the new user as it may have moved */
2098
2099 userrec* ReHashNick(char* Old, char* New)
2100 {
2101         user_hash::iterator newnick;
2102         user_hash::iterator oldnick = clientlist.find(Old);
2103
2104         log(DEBUG,"ReHashNick: %s %s",Old,New);
2105         
2106         if (!strcasecmp(Old,New))
2107         {
2108                 log(DEBUG,"old nick is new nick, skipping");
2109                 return oldnick->second;
2110         }
2111         
2112         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2113
2114         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2115
2116         clientlist[New] = new userrec();
2117         clientlist[New] = oldnick->second;
2118         clientlist.erase(oldnick);
2119
2120         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2121         
2122         return clientlist[New];
2123 }
2124
2125 /* adds or updates an entry in the whowas list */
2126 void AddWhoWas(userrec* u)
2127 {
2128         user_hash::iterator iter = whowas.find(u->nick);
2129         userrec *a = new userrec();
2130         strlcpy(a->nick,u->nick,NICKMAX);
2131         strlcpy(a->ident,u->ident,64);
2132         strlcpy(a->dhost,u->dhost,256);
2133         strlcpy(a->host,u->host,256);
2134         strlcpy(a->fullname,u->fullname,128);
2135         strlcpy(a->server,u->server,256);
2136         a->signon = u->signon;
2137
2138         /* MAX_WHOWAS:   max number of /WHOWAS items
2139          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2140          *               can be replaced by a newer one
2141          */
2142         
2143         if (iter == whowas.end())
2144         {
2145                 if (whowas.size() == WHOWAS_MAX)
2146                 {
2147                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2148                         {
2149                                 // 3600 seconds in an hour ;)
2150                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2151                                 {
2152                                         if (i->second) delete i->second;
2153                                         i->second = a;
2154                                         log(DEBUG,"added WHOWAS entry, purged an old record");
2155                                         return;
2156                                 }
2157                         }
2158                 }
2159                 else
2160                 {
2161                         log(DEBUG,"added fresh WHOWAS entry");
2162                         whowas[a->nick] = a;
2163                 }
2164         }
2165         else
2166         {
2167                 log(DEBUG,"updated WHOWAS entry");
2168                 if (iter->second) delete iter->second;
2169                 iter->second = a;
2170         }
2171 }
2172
2173
2174 /* add a client connection to the sockets list */
2175 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2176 {
2177         int i;
2178         int blocking = 1;
2179         char resolved[MAXBUF];
2180         string tempnick;
2181         char tn2[MAXBUF];
2182         user_hash::iterator iter;
2183
2184         tempnick = ConvToStr(socket) + "-unknown";
2185         sprintf(tn2,"%d-unknown",socket);
2186
2187         iter = clientlist.find(tempnick);
2188
2189         if (iter != clientlist.end()) return;
2190
2191         /*
2192          * It is OK to access the value here this way since we know
2193          * it exists, we just created it above.
2194          *
2195          * At NO other time should you access a value in a map or a
2196          * hash_map this way.
2197          */
2198         clientlist[tempnick] = new userrec();
2199
2200         NonBlocking(socket);
2201         log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2202
2203         clientlist[tempnick]->fd = socket;
2204         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2205         strncpy(clientlist[tempnick]->host, host,160);
2206         strncpy(clientlist[tempnick]->dhost, host,160);
2207         strncpy(clientlist[tempnick]->server, ServerName,256);
2208         strncpy(clientlist[tempnick]->ident, "unknown",9);
2209         clientlist[tempnick]->registered = 0;
2210         clientlist[tempnick]->signon = time(NULL);
2211         clientlist[tempnick]->nping = time(NULL)+240;
2212         clientlist[tempnick]->lastping = 1;
2213         clientlist[tempnick]->port = port;
2214         strncpy(clientlist[tempnick]->ip,ip,32);
2215
2216         lookup_dns(clientlist[tempnick]);
2217
2218         // set the registration timeout for this user
2219         unsigned long class_regtimeout = 90;
2220         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2221         {
2222                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2223                 {
2224                         class_regtimeout = (unsigned long)i->registration_timeout;
2225                         break;
2226                 }
2227         }
2228
2229         int class_flood = 0;
2230         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2231         {
2232                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2233                 {
2234                         class_flood = i->flood;
2235                         break;
2236                 }
2237         }
2238
2239         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2240         clientlist[tempnick]->flood = class_flood;
2241
2242         for (int i = 0; i < MAXCHANS; i++)
2243         {
2244                 clientlist[tempnick]->chans[i].channel = NULL;
2245                 clientlist[tempnick]->chans[i].uc_modes = 0;
2246         }
2247
2248         if (clientlist.size() == MAXCLIENTS)
2249                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2250                 
2251         char* r = matches_zline(ip);
2252         if (r)
2253         {
2254                 char reason[MAXBUF];
2255                 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2256                 kill_link(clientlist[tempnick],reason);
2257         }
2258 }
2259
2260
2261 int usercnt(void)
2262 {
2263         return clientlist.size();
2264 }
2265
2266
2267 int usercount_invisible(void)
2268 {
2269         int c = 0;
2270
2271         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2272         {
2273                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2274         }
2275         return c;
2276 }
2277
2278 int usercount_opers(void)
2279 {
2280         int c = 0;
2281
2282         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2283         {
2284                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2285         }
2286         return c;
2287 }
2288
2289 int usercount_unknown(void)
2290 {
2291         int c = 0;
2292
2293         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2294         {
2295                 if ((i->second->fd) && (i->second->registered != 7))
2296                         c++;
2297         }
2298         return c;
2299 }
2300
2301 long chancount(void)
2302 {
2303         return chanlist.size();
2304 }
2305
2306 long count_servs(void)
2307 {
2308         int c = 0;
2309         //for (int j = 0; j < 255; j++)
2310         //{
2311         //      if (servers[j] != NULL)
2312         //              c++;
2313         //}
2314         return c;
2315 }
2316
2317 long servercount(void)
2318 {
2319         return count_servs()+1;
2320 }
2321
2322 long local_count()
2323 {
2324         int c = 0;
2325         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2326         {
2327                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2328         }
2329         return c;
2330 }
2331
2332
2333 void ShowMOTD(userrec *user)
2334 {
2335         if (!MOTD.size())
2336         {
2337                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2338                 return;
2339         }
2340         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2341         for (int i = 0; i != MOTD.size(); i++)
2342         {
2343                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2344         }
2345         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2346 }
2347
2348 void ShowRULES(userrec *user)
2349 {
2350         if (!RULES.size())
2351         {
2352                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2353                 return;
2354         }
2355         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2356         for (int i = 0; i != RULES.size(); i++)
2357         {
2358                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2359         }
2360         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2361 }
2362
2363 /* shows the message of the day, and any other on-logon stuff */
2364 void FullConnectUser(userrec* user)
2365 {
2366         user->registered = 7;
2367         user->idle_lastmsg = time(NULL);
2368         log(DEBUG,"ConnectUser: %s",user->nick);
2369
2370         if (strcmp(Passwd(user),"") && (!user->haspassed))
2371         {
2372                 kill_link(user,"Invalid password");
2373                 return;
2374         }
2375         if (IsDenied(user))
2376         {
2377                 kill_link(user,"Unauthorised connection");
2378                 return;
2379         }
2380
2381         char match_against[MAXBUF];
2382         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2383         char* r = matches_gline(match_against);
2384         if (r)
2385         {
2386                 char reason[MAXBUF];
2387                 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2388                 kill_link_silent(user,reason);
2389                 return;
2390         }
2391
2392         r = matches_kline(user->host);
2393         if (r)
2394         {
2395                 char reason[MAXBUF];
2396                 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2397                 kill_link_silent(user,reason);
2398                 return;
2399         }
2400
2401         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2402         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2403         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2404         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2405         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2406         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2407         std::stringstream v;
2408         v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2409         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2410         v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2411         v << std::string(Network);
2412         std::string data005 = v.str();
2413         FOREACH_MOD On005Numeric(data005);
2414         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2415         // so i'd better split it :)
2416         std::stringstream out(data005);
2417         std::string token = "";
2418         std::string line5 = "";
2419         int token_counter = 0;
2420         while (!out.eof())
2421         {
2422                 out >> token;
2423                 line5 = line5 + token + " ";
2424                 token_counter++;
2425                 if ((token_counter >= 13) || (out.eof() == true))
2426                 {
2427                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2428                         line5 = "";
2429                         token_counter = 0;
2430                 }
2431         }
2432         ShowMOTD(user);
2433         FOREACH_MOD OnUserConnect(user);
2434         WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2435
2436         char buffer[MAXBUF];
2437         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);
2438         NetSendToAll(buffer);
2439 }
2440
2441 // handles any connects where DNS isnt done yet, times out stale dns queries on users, and lets completed queries connect.
2442 void HandlePendingConnects()
2443 {
2444         if (pending_connects.size())
2445         {
2446                 for (std::vector<userrec*>::iterator i = pending_connects.begin(); i <= pending_connects.end(); i++)
2447                 {
2448                         userrec* a = *i;
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.erase(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.erase(i);
2464                                         return;
2465                                 }
2466                         }
2467                         else
2468                         {
2469                                 pending_connects.erase(i);
2470                                 return;
2471                         }
2472                 }
2473         }
2474 }
2475
2476 /* shows the message of the day, and any other on-logon stuff */
2477 void ConnectUser(userrec *user)
2478 {
2479         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2480         if (user->dns_done)
2481         {
2482                 FullConnectUser(user);
2483         }
2484         else
2485         {
2486                 // add them to the pending queue
2487                 pending_connects.push_back(user);
2488         }
2489 }
2490
2491 void handle_version(char **parameters, int pcnt, userrec *user)
2492 {
2493         char Revision[] = "$Revision$";
2494
2495         char *s1 = Revision;
2496         char *savept;
2497         char *v1 = strtok_r(s1," ",&savept);
2498         s1 = savept;
2499         char *v2 = strtok_r(s1," ",&savept);
2500         s1 = savept;
2501         
2502         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2503 }
2504
2505
2506 // calls a handler function for a command
2507
2508 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2509 {
2510                 for (int i = 0; i < cmdlist.size(); i++)
2511                 {
2512                         if (!strcasecmp(cmdlist[i].command,commandname))
2513                         {
2514                                 if (cmdlist[i].handler_function)
2515                                 {
2516                                         if (pcnt>=cmdlist[i].min_params)
2517                                         {
2518                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2519                                                 {
2520                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2521                                                 }
2522                                         }
2523                                 }
2524                         }
2525                 }
2526 }
2527
2528 void DoSplitEveryone()
2529 {
2530         bool go_again = true;
2531         while (go_again)
2532         {
2533                 go_again = false;
2534                 for (int i = 0; i < 32; i++)
2535                 {
2536                         if (me[i] != NULL)
2537                         {
2538                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2539                                 {
2540                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2541                                         {
2542                                                 j->routes.clear();
2543                                                 j->CloseConnection();
2544                                                 me[i]->connectors.erase(j);
2545                                                 go_again = true;
2546                                                 break;
2547                                         }
2548                                 }
2549                         }
2550                 }
2551         }
2552         log(DEBUG,"Removed server. Will remove clients...");
2553         // iterate through the userlist and remove all users on this server.
2554         // because we're dealing with a mesh, we dont have to deal with anything
2555         // "down-route" from this server (nice huh)
2556         go_again = true;
2557         char reason[MAXBUF];
2558         while (go_again)
2559         {
2560                 go_again = false;
2561                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2562                 {
2563                         if (strcasecmp(u->second->server,ServerName))
2564                         {
2565                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2566                                 kill_link(u->second,reason);
2567                                 go_again = true;
2568                                 break;
2569                         }
2570                 }
2571         }
2572 }
2573
2574
2575
2576 char islast(const char* s)
2577 {
2578         char c = '`';
2579         for (int j = 0; j < 32; j++)
2580         {
2581                 if (me[j] != NULL)
2582                 {
2583                         for (int k = 0; k < me[j]->connectors.size(); k++)
2584                         {
2585                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2586                                 {
2587                                         c = '|';
2588                                 }
2589                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2590                                 {
2591                                         c = '`';
2592                                 }
2593                         }
2594                 }
2595         }
2596         return c;
2597 }
2598
2599 long map_count(const char* s)
2600 {
2601         int c = 0;
2602         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2603         {
2604                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2605         }
2606         return c;
2607 }
2608
2609
2610 void force_nickchange(userrec* user,const char* newnick)
2611 {
2612         char nick[MAXBUF];
2613         int MOD_RESULT = 0;
2614         
2615         strcpy(nick,"");
2616
2617         FOREACH_RESULT(OnUserPreNick(user,newnick));
2618         if (MOD_RESULT) {
2619                 kill_link(user,"Nickname collision");
2620                 return;
2621         }
2622         if (matches_qline(newnick))
2623         {
2624                 kill_link(user,"Nickname collision");
2625                 return;
2626         }
2627         
2628         if (user)
2629         {
2630                 if (newnick)
2631                 {
2632                         strncpy(nick,newnick,MAXBUF);
2633                 }
2634                 if (user->registered == 7)
2635                 {
2636                         char* pars[1];
2637                         pars[0] = nick;
2638                         handle_nick(pars,1,user);
2639                 }
2640         }
2641 }
2642                                 
2643
2644 int process_parameters(char **command_p,char *parameters)
2645 {
2646         int i = 0;
2647         int j = 0;
2648         int q = 0;
2649         q = strlen(parameters);
2650         if (!q)
2651         {
2652                 /* no parameters, command_p invalid! */
2653                 return 0;
2654         }
2655         if (parameters[0] == ':')
2656         {
2657                 command_p[0] = parameters+1;
2658                 return 1;
2659         }
2660         if (q)
2661         {
2662                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2663                 {
2664                         /* only one parameter */
2665                         command_p[0] = parameters;
2666                         if (parameters[0] == ':')
2667                         {
2668                                 if (strchr(parameters,' ') != NULL)
2669                                 {
2670                                         command_p[0]++;
2671                                 }
2672                         }
2673                         return 1;
2674                 }
2675         }
2676         command_p[j++] = parameters;
2677         for (int i = 0; i <= q; i++)
2678         {
2679                 if (parameters[i] == ' ')
2680                 {
2681                         command_p[j++] = parameters+i+1;
2682                         parameters[i] = '\0';
2683                         if (command_p[j-1][0] == ':')
2684                         {
2685                                 *command_p[j-1]++; /* remove dodgy ":" */
2686                                 break;
2687                                 /* parameter like this marks end of the sequence */
2688                         }
2689                 }
2690         }
2691         return j; /* returns total number of items in the list */
2692 }
2693
2694 void process_command(userrec *user, char* cmd)
2695 {
2696         char *parameters;
2697         char *command;
2698         char *command_p[127];
2699         char p[MAXBUF], temp[MAXBUF];
2700         int i, j, items, cmd_found;
2701
2702         for (int i = 0; i < 127; i++)
2703                 command_p[i] = NULL;
2704
2705         if (!user)
2706         {
2707                 return;
2708         }
2709         if (!cmd)
2710         {
2711                 return;
2712         }
2713         if (!strcmp(cmd,""))
2714         {
2715                 return;
2716         }
2717         
2718         int total_params = 0;
2719         if (strlen(cmd)>2)
2720         {
2721                 for (int q = 0; q < strlen(cmd)-1; q++)
2722                 {
2723                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2724                         {
2725                                 total_params++;
2726                                 // found a 'trailing', we dont count them after this.
2727                                 break;
2728                         }
2729                         if (cmd[q] == ' ')
2730                                 total_params++;
2731                 }
2732         }
2733         
2734         // another phidjit bug...
2735         if (total_params > 126)
2736         {
2737                 //kill_link(user,"Protocol violation (1)");
2738                 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2739                 return;
2740         }
2741         
2742         strlcpy(temp,cmd,MAXBUF);
2743
2744         std::string tmp = cmd;
2745         for (int i = 0; i <= MODCOUNT; i++)
2746         {
2747                 std::string oldtmp = tmp;
2748                 modules[i]->OnServerRaw(tmp,true,user);
2749                 if (oldtmp != tmp)
2750                 {
2751                         log(DEBUG,"A Module changed the input string!");
2752                         log(DEBUG,"New string: %s",tmp.c_str());
2753                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2754                         break;
2755                 }
2756         }
2757         strlcpy(cmd,tmp.c_str(),MAXBUF);
2758         strlcpy(temp,cmd,MAXBUF);
2759
2760         if (!strchr(cmd,' '))
2761         {
2762                 /* no parameters, lets skip the formalities and not chop up
2763                  * the string */
2764                 log(DEBUG,"About to preprocess command with no params");
2765                 items = 0;
2766                 command_p[0] = NULL;
2767                 parameters = NULL;
2768                 for (int i = 0; i <= strlen(cmd); i++)
2769                 {
2770                         cmd[i] = toupper(cmd[i]);
2771                 }
2772                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2773                 command = cmd;
2774         }
2775         else
2776         {
2777                 strcpy(cmd,"");
2778                 j = 0;
2779                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2780                 for (int i = 0; i < strlen(temp); i++)
2781                 {
2782                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2783                         {
2784                                 cmd[j++] = temp[i];
2785                                 cmd[j] = 0;
2786                         }
2787                 }
2788                 /* split the full string into a command plus parameters */
2789                 parameters = p;
2790                 strcpy(p," ");
2791                 command = cmd;
2792                 if (strchr(cmd,' '))
2793                 {
2794                         for (int i = 0; i <= strlen(cmd); i++)
2795                         {
2796                                 /* capitalise the command ONLY, leave params intact */
2797                                 cmd[i] = toupper(cmd[i]);
2798                                 /* are we nearly there yet?! :P */
2799                                 if (cmd[i] == ' ')
2800                                 {
2801                                         command = cmd;
2802                                         parameters = cmd+i+1;
2803                                         cmd[i] = '\0';
2804                                         break;
2805                                 }
2806                         }
2807                 }
2808                 else
2809                 {
2810                         for (int i = 0; i <= strlen(cmd); i++)
2811                         {
2812                                 cmd[i] = toupper(cmd[i]);
2813                         }
2814                 }
2815
2816         }
2817         cmd_found = 0;
2818         
2819         if (strlen(command)>MAXCOMMAND)
2820         {
2821                 //kill_link(user,"Protocol violation (2)");
2822                 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2823                 return;
2824         }
2825         
2826         for (int x = 0; x < strlen(command); x++)
2827         {
2828                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2829                 {
2830                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2831                         {
2832                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2833                                 {
2834                                         //kill_link(user,"Protocol violation (3)");
2835                                         WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2836                                         return;
2837                                 }
2838                         }
2839                 }
2840         }
2841
2842         for (int i = 0; i != cmdlist.size(); i++)
2843         {
2844                 if (strcmp(cmdlist[i].command,""))
2845                 {
2846                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2847                         {
2848                                 log(DEBUG,"Found matching command");
2849
2850                                 if (parameters)
2851                                 {
2852                                         if (strcmp(parameters,""))
2853                                         {
2854                                                 items = process_parameters(command_p,parameters);
2855                                         }
2856                                         else
2857                                         {
2858                                                 items = 0;
2859                                                 command_p[0] = NULL;
2860                                         }
2861                                 }
2862                                 else
2863                                 {
2864                                         items = 0;
2865                                         command_p[0] = NULL;
2866                                 }
2867                                 
2868                                 if (user)
2869                                 {
2870                                         log(DEBUG,"Processing command");
2871                                         
2872                                         /* activity resets the ping pending timer */
2873                                         user->nping = time(NULL) + 120;
2874                                         if ((items) < cmdlist[i].min_params)
2875                                         {
2876                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2877                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2878                                                 return;
2879                                         }
2880                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2881                                         {
2882                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2883                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2884                                                 cmd_found = 1;
2885                                                 return;
2886                                         }
2887                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2888                                         {
2889                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2890                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2891                                                 cmd_found = 1;
2892                                                 return;
2893                                         }
2894                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2895                                          * deny command! */
2896                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2897                                         {
2898                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2899                                                 {
2900                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2901                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2902                                                         return;
2903                                                 }
2904                                         }
2905                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2906                                         {
2907                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2908                                                 if (cmdlist[i].handler_function)
2909                                                 {
2910                                                         /* ikky /stats counters */
2911                                                         if (temp)
2912                                                         {
2913                                                                 if (user)
2914                                                                 {
2915                                                                         user->bytes_in += strlen(temp);
2916                                                                         user->cmds_in++;
2917                                                                 }
2918                                                                 cmdlist[i].use_count++;
2919                                                                 cmdlist[i].total_bytes+=strlen(temp);
2920                                                         }
2921
2922                                                         /* WARNING: nothing may come after the
2923                                                          * command handler call, as the handler
2924                                                          * may free the user structure! */
2925
2926                                                         cmdlist[i].handler_function(command_p,items,user);
2927                                                 }
2928                                                 return;
2929                                         }
2930                                         else
2931                                         {
2932                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2933                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2934                                                 return;
2935                                         }
2936                                 }
2937                                 cmd_found = 1;
2938                         }
2939                 }
2940         }
2941         if ((!cmd_found) && (user))
2942         {
2943                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2944                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2945         }
2946 }
2947
2948
2949 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2950 {
2951         command_t comm;
2952         /* create the command and push it onto the table */     
2953         strlcpy(comm.command,cmd,MAXBUF);
2954         comm.handler_function = f;
2955         comm.flags_needed = flags;
2956         comm.min_params = minparams;
2957         comm.use_count = 0;
2958         comm.total_bytes = 0;
2959         cmdlist.push_back(comm);
2960         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2961 }
2962
2963 void SetupCommandTable(void)
2964 {
2965         createcommand("USER",handle_user,0,4);
2966         createcommand("NICK",handle_nick,0,1);
2967         createcommand("QUIT",handle_quit,0,0);
2968         createcommand("VERSION",handle_version,0,0);
2969         createcommand("PING",handle_ping,0,1);
2970         createcommand("PONG",handle_pong,0,1);
2971         createcommand("ADMIN",handle_admin,0,0);
2972         createcommand("PRIVMSG",handle_privmsg,0,2);
2973         createcommand("INFO",handle_info,0,0);
2974         createcommand("TIME",handle_time,0,0);
2975         createcommand("WHOIS",handle_whois,0,1);
2976         createcommand("WALLOPS",handle_wallops,'o',1);
2977         createcommand("NOTICE",handle_notice,0,2);
2978         createcommand("JOIN",handle_join,0,1);
2979         createcommand("NAMES",handle_names,0,1);
2980         createcommand("PART",handle_part,0,1);
2981         createcommand("KICK",handle_kick,0,2);
2982         createcommand("MODE",handle_mode,0,1);
2983         createcommand("TOPIC",handle_topic,0,1);
2984         createcommand("WHO",handle_who,0,1);
2985         createcommand("MOTD",handle_motd,0,0);
2986         createcommand("RULES",handle_rules,0,0);
2987         createcommand("OPER",handle_oper,0,2);
2988         createcommand("LIST",handle_list,0,0);
2989         createcommand("DIE",handle_die,'o',1);
2990         createcommand("RESTART",handle_restart,'o',1);
2991         createcommand("KILL",handle_kill,'o',2);
2992         createcommand("REHASH",handle_rehash,'o',0);
2993         createcommand("LUSERS",handle_lusers,0,0);
2994         createcommand("STATS",handle_stats,0,1);
2995         createcommand("USERHOST",handle_userhost,0,1);
2996         createcommand("AWAY",handle_away,0,0);
2997         createcommand("ISON",handle_ison,0,0);
2998         createcommand("SUMMON",handle_summon,0,0);
2999         createcommand("USERS",handle_users,0,0);
3000         createcommand("INVITE",handle_invite,0,2);
3001         createcommand("PASS",handle_pass,0,1);
3002         createcommand("TRACE",handle_trace,'o',0);
3003         createcommand("WHOWAS",handle_whowas,0,1);
3004         createcommand("CONNECT",handle_connect,'o',1);
3005         createcommand("SQUIT",handle_squit,'o',0);
3006         createcommand("MODULES",handle_modules,'o',0);
3007         createcommand("LINKS",handle_links,0,0);
3008         createcommand("MAP",handle_map,0,0);
3009         createcommand("KLINE",handle_kline,'o',1);
3010         createcommand("GLINE",handle_gline,'o',1);
3011         createcommand("ZLINE",handle_zline,'o',1);
3012         createcommand("QLINE",handle_qline,'o',1);
3013         createcommand("SERVER",handle_server,0,0);
3014 }
3015
3016 void process_buffer(const char* cmdbuf,userrec *user)
3017 {
3018         if (!user)
3019         {
3020                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3021                 return;
3022         }
3023         char cmd[MAXBUF];
3024         int i;
3025         if (!cmdbuf)
3026         {
3027                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3028                 return;
3029         }
3030         if (!strcmp(cmdbuf,""))
3031         {
3032                 return;
3033         }
3034         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3035
3036         strlcpy(cmd,cmdbuf,MAXBUF);
3037         if (!strcmp(cmd,""))
3038         {
3039                 return;
3040         }
3041         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3042         {
3043                 cmd[strlen(cmd)-1] = '\0';
3044         }
3045         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3046         {
3047                 cmd[strlen(cmd)-1] = '\0';
3048         }
3049
3050         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3051         {
3052                 cmd[strlen(cmd)-1] = '\0';
3053         }
3054
3055         if (!strcmp(cmd,""))
3056         {
3057                 return;
3058         }
3059         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3060         tidystring(cmd);
3061         if ((user) && (cmd))
3062         {
3063                 process_command(user,cmd);
3064         }
3065 }
3066
3067 void DoSync(serverrec* serv, char* tcp_host)
3068 {
3069         char data[MAXBUF];
3070         log(DEBUG,"Sending sync");
3071         // send start of sync marker: Y <timestamp>
3072         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3073         // except the ones its receiving it from.
3074         snprintf(data,MAXBUF,"Y %d",time(NULL));
3075         serv->SendPacket(data,tcp_host);
3076         // send users and channels
3077         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3078         {
3079                 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);
3080                 serv->SendPacket(data,tcp_host);
3081                 if (strchr(u->second->modes,'o'))
3082                 {
3083                         snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3084                         serv->SendPacket(data,tcp_host);
3085                 }
3086                 for (int i = 0; i <= MODCOUNT; i++)
3087                 {
3088                         string_list l = modules[i]->OnUserSync(u->second);
3089                         for (int j = 0; j < l.size(); j++)
3090                         {
3091                                 strlcpy(data,l[j].c_str(),MAXBUF);
3092                                 serv->SendPacket(data,tcp_host);
3093                         }
3094                 }
3095                 if (strcmp(chlist(u->second),""))
3096                 {
3097                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3098                         serv->SendPacket(data,tcp_host);
3099                 }
3100         }
3101         // send channel modes, topics etc...
3102         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3103         {
3104                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3105                 serv->SendPacket(data,tcp_host);
3106                 for (int i = 0; i <= MODCOUNT; i++)
3107                 {
3108                         string_list l = modules[i]->OnChannelSync(c->second);
3109                         for (int j = 0; j < l.size(); j++)
3110                         {
3111                                 strlcpy(data,l[j].c_str(),MAXBUF);
3112                                 serv->SendPacket(data,tcp_host);
3113                         }
3114                 }
3115                 if (strcmp(c->second->topic,""))
3116                 {
3117                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3118                         serv->SendPacket(data,tcp_host);
3119                 }
3120                 // send current banlist
3121                 
3122                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3123                 {
3124                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3125                         serv->SendPacket(data,tcp_host);
3126                 }
3127         }
3128         // sync global zlines, glines, etc
3129         sync_xlines(serv,tcp_host);
3130
3131         for (int j = 0; j < 32; j++)
3132         {
3133                 if (me[j] != NULL)
3134                 {
3135                         for (int k = 0; k < me[j]->connectors.size(); k++)
3136                         {
3137                                 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3138                                 {
3139                                         snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3140                                         serv->SendPacket(data,tcp_host);
3141                                         NetSendMyRoutingTable();
3142                                 }
3143                         }
3144                 }
3145         }
3146
3147         snprintf(data,MAXBUF,"F %d",time(NULL));
3148         serv->SendPacket(data,tcp_host);
3149         log(DEBUG,"Sent sync");
3150         // ircd sends its serverlist after the end of sync here
3151 }
3152
3153
3154 void NetSendMyRoutingTable()
3155 {
3156         // send out a line saying what is reachable to us.
3157         // E.g. if A is linked to B C and D, send out:
3158         // $ A B C D
3159         // if its only linked to B and D send out:
3160         // $ A B D
3161         // if it has no links, dont even send out the line at all.
3162         char buffer[MAXBUF];
3163         snprintf(buffer,MAXBUF,"$ %s",ServerName);
3164         bool sendit = false;
3165         for (int i = 0; i < 32; i++)
3166         {
3167                 if (me[i] != NULL)
3168                 {
3169                         for (int j = 0; j < me[i]->connectors.size(); j++)
3170                         {
3171                                 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3172                                 {
3173                                         strlcat(buffer," ",MAXBUF);
3174                                         strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3175                                         sendit = true;
3176                                 }
3177                         }
3178                 }
3179         }
3180         if (sendit)
3181                 NetSendToAll(buffer);
3182 }
3183
3184
3185 void DoSplit(const char* params)
3186 {
3187         bool go_again = true;
3188         while (go_again)
3189         {
3190                 go_again = false;
3191                 for (int i = 0; i < 32; i++)
3192                 {
3193                         if (me[i] != NULL)
3194                         {
3195                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3196                                 {
3197                                         if (!strcasecmp(j->GetServerName().c_str(),params))
3198                                         {
3199                                                 j->routes.clear();
3200                                                 j->CloseConnection();
3201                                                 me[i]->connectors.erase(j);
3202                                                 go_again = true;
3203                                                 break;
3204                                         }
3205                                 }
3206                         }
3207                 }
3208         }
3209         log(DEBUG,"Removed server. Will remove clients...");
3210         // iterate through the userlist and remove all users on this server.
3211         // because we're dealing with a mesh, we dont have to deal with anything
3212         // "down-route" from this server (nice huh)
3213         go_again = true;
3214         char reason[MAXBUF];
3215         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3216         while (go_again)
3217         {
3218                 go_again = false;
3219                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3220                 {
3221                         if (!strcasecmp(u->second->server,params))
3222                         {
3223                                 kill_link(u->second,reason);
3224                                 go_again = true;
3225                                 break;
3226                         }
3227                 }
3228         }
3229 }
3230
3231 // removes a server. Will NOT remove its users!
3232
3233 void RemoveServer(const char* name)
3234 {
3235         bool go_again = true;
3236         while (go_again)
3237         {
3238                 go_again = false;
3239                 for (int i = 0; i < 32; i++)
3240                 {
3241                         if (me[i] != NULL)
3242                         {
3243                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3244                                 {
3245                                         if (!strcasecmp(j->GetServerName().c_str(),name))
3246                                         {
3247                                                 j->routes.clear();
3248                                                 j->CloseConnection();
3249                                                 me[i]->connectors.erase(j);
3250                                                 go_again = true;
3251                                                 break;
3252                                         }
3253                                 }
3254                         }
3255                 }
3256         }
3257 }
3258
3259
3260 int reap_counter = 0;
3261
3262 int InspIRCd(void)
3263 {
3264         struct sockaddr_in client,server;
3265         char addrs[MAXBUF][255];
3266         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3267         socklen_t length;
3268         int count = 0;
3269         int selectResult = 0, selectResult2 = 0;
3270         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3271         char resolvedHost[MAXBUF];
3272         fd_set selectFds;
3273         struct timeval tv;
3274
3275         log_file = fopen("ircd.log","a+");
3276         if (!log_file)
3277         {
3278                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3279                 Exit(ERROR);
3280         }
3281
3282         log(DEBUG,"InspIRCd: startup: begin");
3283         log(DEBUG,"$Id$");
3284         if (geteuid() == 0)
3285         {
3286                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3287                 Exit(ERROR);
3288                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3289         }
3290         SetupCommandTable();
3291         log(DEBUG,"InspIRCd: startup: default command table set up");
3292         
3293         ReadConfig(true,NULL);
3294         if (strcmp(DieValue,"")) 
3295         { 
3296                 printf("WARNING: %s\n\n",DieValue);
3297                 exit(0); 
3298         }  
3299         log(DEBUG,"InspIRCd: startup: read config");
3300           
3301         int count2 = 0, count3 = 0;
3302
3303         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3304         {
3305                 ConfValue("bind","port",count,configToken,&config_f);
3306                 ConfValue("bind","address",count,Addr,&config_f);
3307                 ConfValue("bind","type",count,Type,&config_f);
3308                 if (!strcmp(Type,"servers"))
3309                 {
3310                         char Default[MAXBUF];
3311                         strcpy(Default,"no");
3312                         ConfValue("bind","default",count,Default,&config_f);
3313                         if (strchr(Default,'y'))
3314                         {
3315                                 defaultRoute = count3;
3316                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3317                         }
3318                         me[count3] = new serverrec(ServerName,100L,false);
3319                         if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3320                         {
3321                                 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3322                         }
3323                         else
3324                         {
3325                                 count3++;
3326                         }
3327                 }
3328                 else
3329                 {
3330                         ports[count2] = atoi(configToken);
3331                         strlcpy(addrs[count2],Addr,256);
3332                         count2++;
3333                 }
3334                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3335         }
3336         portCount = count2;
3337         UDPportCount = count3;
3338           
3339         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3340         
3341         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3342         
3343         printf("\n");
3344         
3345         /* BugFix By Craig! :p */
3346         count = 0;
3347         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3348         {
3349                 char modfile[MAXBUF];
3350                 ConfValue("module","name",count2,configToken,&config_f);
3351                 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3352                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3353                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3354                 /* If The File Doesnt exist, Trying to load it
3355                  * Will Segfault the IRCd.. So, check to see if
3356                  * it Exists, Before Proceeding. */
3357                 if (FileExists(modfile))
3358                 {
3359                         factory[count] = new ircd_module(modfile);
3360                         if (factory[count]->LastError())
3361                         {
3362                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3363                                 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3364                                 Exit(ERROR);
3365                         }
3366                         if (factory[count]->factory)
3367                         {
3368                                 modules[count] = factory[count]->factory->CreateModule();
3369                                 /* save the module and the module's classfactory, if
3370                                  * this isnt done, random crashes can occur :/ */
3371                                 module_names.push_back(modfile);        
3372                         }
3373                         else
3374                         {
3375                                 log(DEBUG,"Unable to load %s",modfile);
3376                                 printf("Unable to load %s\nExiting...\n",modfile);
3377                                 Exit(ERROR);
3378                         }
3379                         /* Increase the Count */
3380                         count++;
3381                 }
3382                 else
3383                 {
3384                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3385                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3386                 }
3387         }
3388         MODCOUNT = count - 1;
3389         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3390         
3391         printf("\nInspIRCd is now running!\n");
3392         
3393         startup_time = time(NULL);
3394           
3395         if (nofork)
3396         {
3397                 log(VERBOSE,"Not forking as -nofork was specified");
3398         }
3399         else
3400         {
3401                 if (DaemonSeed() == ERROR)
3402                 {
3403                         log(DEBUG,"InspIRCd: startup: can't daemonise");
3404                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3405                         Exit(ERROR);
3406                 }
3407         }
3408           
3409           
3410         /* setup select call */
3411         FD_ZERO(&selectFds);
3412         log(DEBUG,"InspIRCd: startup: zero selects");
3413         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3414         
3415         for (count = 0; count < portCount; count++)
3416         {
3417                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3418                 {
3419                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3420                         return(ERROR);
3421                 }
3422                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3423                 {
3424                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3425                 }
3426                 else    /* well we at least bound to one socket so we'll continue */
3427                 {
3428                         boundPortCount++;
3429                 }
3430         }
3431         
3432         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3433           
3434         /* if we didn't bind to anything then abort */
3435         if (boundPortCount == 0)
3436         {
3437                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3438                 return (ERROR);
3439         }
3440         
3441
3442         length = sizeof (client);
3443         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3444           
3445         /* main loop, this never returns */
3446         for (;;)
3447         {
3448 #ifdef _POSIX_PRIORITY_SCHEDULING
3449                 sched_yield();
3450 #endif
3451                 // update the status of klines, etc
3452                 expire_lines();
3453
3454                 fd_set sfd;
3455                 timeval tval;
3456                 FD_ZERO(&sfd);
3457
3458                 // poll dns queue
3459                 dns_poll();
3460
3461                 // handle pending connects
3462                 HandlePendingConnects();
3463
3464                 user_hash::iterator count2 = clientlist.begin();
3465
3466                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3467                 // them in a list, then reap the list every second or so.
3468                 if (reap_counter>300)
3469                 {
3470                         if (fd_reap.size() > 0)
3471                         {
3472                                 for( int n = 0; n < fd_reap.size(); n++)
3473                                 {
3474                                         Blocking(fd_reap[n]);
3475                                         close(fd_reap[n]);
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