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