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