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