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