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