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