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