]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
de5420ddb717a5f68090d4e9e40b1c0d9ac89678
[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         //      if (servers[j] != NULL)
2464         //              c++;
2465         //}
2466         return c;
2467 }
2468
2469 long servercount(void)
2470 {
2471         return count_servs()+1;
2472 }
2473
2474 long local_count()
2475 {
2476         int c = 0;
2477         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2478         {
2479                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2480         }
2481         return c;
2482 }
2483
2484
2485 void ShowMOTD(userrec *user)
2486 {
2487         std::string WholeMOTD = "";
2488         if (!MOTD.size())
2489         {
2490                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2491                 return;
2492         }
2493         WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2494         for (int i = 0; i != MOTD.size(); i++)
2495         {
2496                 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2497         }
2498         WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2499         // only one write operation
2500         send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
2501
2502 }
2503
2504 void ShowRULES(userrec *user)
2505 {
2506         if (!RULES.size())
2507         {
2508                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2509                 return;
2510         }
2511         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2512         for (int i = 0; i != RULES.size(); i++)
2513         {
2514                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2515         }
2516         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2517 }
2518
2519 /* shows the message of the day, and any other on-logon stuff */
2520 void FullConnectUser(userrec* user)
2521 {
2522         user->registered = 7;
2523         user->idle_lastmsg = TIME;
2524         log(DEBUG,"ConnectUser: %s",user->nick);
2525
2526         if (strcmp(Passwd(user),"") && (!user->haspassed))
2527         {
2528                 kill_link(user,"Invalid password");
2529                 return;
2530         }
2531         if (IsDenied(user))
2532         {
2533                 kill_link(user,"Unauthorised connection");
2534                 return;
2535         }
2536
2537         char match_against[MAXBUF];
2538         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2539         char* e = matches_exception(match_against);
2540         if (!e)
2541         {
2542                 char* r = matches_gline(match_against);
2543                 if (r)
2544                 {
2545                         char reason[MAXBUF];
2546                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
2547                         kill_link_silent(user,reason);
2548                         return;
2549                 }
2550                 r = matches_kline(user->host);
2551                 if (r)
2552                 {
2553                         char reason[MAXBUF];
2554                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
2555                         kill_link_silent(user,reason);
2556                         return;
2557                 }
2558         }
2559
2560         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2561         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2562         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2563         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2564         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2565         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2566         std::stringstream v;
2567         v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2568         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2569         v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2570         v << std::string(Network);
2571         std::string data005 = v.str();
2572         FOREACH_MOD On005Numeric(data005);
2573         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2574         // so i'd better split it :)
2575         std::stringstream out(data005);
2576         std::string token = "";
2577         std::string line5 = "";
2578         int token_counter = 0;
2579         while (!out.eof())
2580         {
2581                 out >> token;
2582                 line5 = line5 + token + " ";
2583                 token_counter++;
2584                 if ((token_counter >= 13) || (out.eof() == true))
2585                 {
2586                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2587                         line5 = "";
2588                         token_counter = 0;
2589                 }
2590         }
2591         ShowMOTD(user);
2592         FOREACH_MOD OnUserConnect(user);
2593         WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2594
2595         char buffer[MAXBUF];
2596         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);
2597         NetSendToAll(buffer);
2598 }
2599
2600
2601 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
2602 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
2603 // registration timeout maximum seconds)
2604 bool AllModulesReportReady(userrec* user)
2605 {
2606         for (int i = 0; i <= MODCOUNT; i++)
2607         {
2608                 int res = modules[i]->OnCheckReady(user);
2609                         if (!res)
2610                                 return false;
2611         }
2612         return true;
2613 }
2614
2615 /* shows the message of the day, and any other on-logon stuff */
2616 void ConnectUser(userrec *user)
2617 {
2618         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2619         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
2620         {
2621                 FullConnectUser(user);
2622         }
2623 }
2624
2625 void handle_version(char **parameters, int pcnt, userrec *user)
2626 {
2627         char Revision[] = "$Revision$";
2628
2629         char *s1 = Revision;
2630         char *savept;
2631         char *v1 = strtok_r(s1," ",&savept);
2632         s1 = savept;
2633         char *v2 = strtok_r(s1," ",&savept);
2634         s1 = savept;
2635         
2636         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2637 }
2638
2639
2640 // calls a handler function for a command
2641
2642 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2643 {
2644                 for (int i = 0; i < cmdlist.size(); i++)
2645                 {
2646                         if (!strcasecmp(cmdlist[i].command,commandname))
2647                         {
2648                                 if (cmdlist[i].handler_function)
2649                                 {
2650                                         if (pcnt>=cmdlist[i].min_params)
2651                                         {
2652                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2653                                                 {
2654                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2655                                                 }
2656                                         }
2657                                 }
2658                         }
2659                 }
2660 }
2661
2662 void DoSplitEveryone()
2663 {
2664         bool go_again = true;
2665         while (go_again)
2666         {
2667                 go_again = false;
2668                 for (int i = 0; i < 32; i++)
2669                 {
2670                         if (me[i] != NULL)
2671                         {
2672                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2673                                 {
2674                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2675                                         {
2676                                                 j->routes.clear();
2677                                                 j->CloseConnection();
2678                                                 me[i]->connectors.erase(j);
2679                                                 go_again = true;
2680                                                 break;
2681                                         }
2682                                 }
2683                         }
2684                 }
2685         }
2686         log(DEBUG,"Removed server. Will remove clients...");
2687         // iterate through the userlist and remove all users on this server.
2688         // because we're dealing with a mesh, we dont have to deal with anything
2689         // "down-route" from this server (nice huh)
2690         go_again = true;
2691         char reason[MAXBUF];
2692         while (go_again)
2693         {
2694                 go_again = false;
2695                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2696                 {
2697                         if (strcasecmp(u->second->server,ServerName))
2698                         {
2699                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2700                                 kill_link(u->second,reason);
2701                                 go_again = true;
2702                                 break;
2703                         }
2704                 }
2705         }
2706 }
2707
2708
2709
2710 char islast(const char* s)
2711 {
2712         char c = '`';
2713         for (int j = 0; j < 32; j++)
2714         {
2715                 if (me[j] != NULL)
2716                 {
2717                         for (int k = 0; k < me[j]->connectors.size(); k++)
2718                         {
2719                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2720                                 {
2721                                         c = '|';
2722                                 }
2723                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2724                                 {
2725                                         c = '`';
2726                                 }
2727                         }
2728                 }
2729         }
2730         return c;
2731 }
2732
2733 long map_count(const char* s)
2734 {
2735         int c = 0;
2736         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2737         {
2738                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2739         }
2740         return c;
2741 }
2742
2743
2744 void force_nickchange(userrec* user,const char* newnick)
2745 {
2746         char nick[MAXBUF];
2747         int MOD_RESULT = 0;
2748         
2749         strcpy(nick,"");
2750
2751         FOREACH_RESULT(OnUserPreNick(user,newnick));
2752         if (MOD_RESULT) {
2753                 kill_link(user,"Nickname collision");
2754                 return;
2755         }
2756         if (matches_qline(newnick))
2757         {
2758                 kill_link(user,"Nickname collision");
2759                 return;
2760         }
2761         
2762         if (user)
2763         {
2764                 if (newnick)
2765                 {
2766                         strncpy(nick,newnick,MAXBUF);
2767                 }
2768                 if (user->registered == 7)
2769                 {
2770                         char* pars[1];
2771                         pars[0] = nick;
2772                         handle_nick(pars,1,user);
2773                 }
2774         }
2775 }
2776                                 
2777
2778 int process_parameters(char **command_p,char *parameters)
2779 {
2780         int i = 0;
2781         int j = 0;
2782         int q = 0;
2783         q = strlen(parameters);
2784         if (!q)
2785         {
2786                 /* no parameters, command_p invalid! */
2787                 return 0;
2788         }
2789         if (parameters[0] == ':')
2790         {
2791                 command_p[0] = parameters+1;
2792                 return 1;
2793         }
2794         if (q)
2795         {
2796                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2797                 {
2798                         /* only one parameter */
2799                         command_p[0] = parameters;
2800                         if (parameters[0] == ':')
2801                         {
2802                                 if (strchr(parameters,' ') != NULL)
2803                                 {
2804                                         command_p[0]++;
2805                                 }
2806                         }
2807                         return 1;
2808                 }
2809         }
2810         command_p[j++] = parameters;
2811         for (int i = 0; i <= q; i++)
2812         {
2813                 if (parameters[i] == ' ')
2814                 {
2815                         command_p[j++] = parameters+i+1;
2816                         parameters[i] = '\0';
2817                         if (command_p[j-1][0] == ':')
2818                         {
2819                                 *command_p[j-1]++; /* remove dodgy ":" */
2820                                 break;
2821                                 /* parameter like this marks end of the sequence */
2822                         }
2823                 }
2824         }
2825         return j; /* returns total number of items in the list */
2826 }
2827
2828 void process_command(userrec *user, char* cmd)
2829 {
2830         char *parameters;
2831         char *command;
2832         char *command_p[127];
2833         char p[MAXBUF], temp[MAXBUF];
2834         int i, j, items, cmd_found;
2835
2836         for (int i = 0; i < 127; i++)
2837                 command_p[i] = NULL;
2838
2839         if (!user)
2840         {
2841                 return;
2842         }
2843         if (!cmd)
2844         {
2845                 return;
2846         }
2847         if (!strcmp(cmd,""))
2848         {
2849                 return;
2850         }
2851         
2852         int total_params = 0;
2853         if (strlen(cmd)>2)
2854         {
2855                 for (int q = 0; q < strlen(cmd)-1; q++)
2856                 {
2857                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2858                         {
2859                                 total_params++;
2860                                 // found a 'trailing', we dont count them after this.
2861                                 break;
2862                         }
2863                         if (cmd[q] == ' ')
2864                                 total_params++;
2865                 }
2866         }
2867
2868         // another phidjit bug...
2869         if (total_params > 126)
2870         {
2871                 *(strchr(cmd,' ')) = '\0';
2872                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
2873                 return;
2874         }
2875
2876         strlcpy(temp,cmd,MAXBUF);
2877         
2878         std::string tmp = cmd;
2879         for (int i = 0; i <= MODCOUNT; i++)
2880         {
2881                 std::string oldtmp = tmp;
2882                 modules[i]->OnServerRaw(tmp,true,user);
2883                 if (oldtmp != tmp)
2884                 {
2885                         log(DEBUG,"A Module changed the input string!");
2886                         log(DEBUG,"New string: %s",tmp.c_str());
2887                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2888                         break;
2889                 }
2890         }
2891         strlcpy(cmd,tmp.c_str(),MAXBUF);
2892         strlcpy(temp,cmd,MAXBUF);
2893
2894         if (!strchr(cmd,' '))
2895         {
2896                 /* no parameters, lets skip the formalities and not chop up
2897                  * the string */
2898                 log(DEBUG,"About to preprocess command with no params");
2899                 items = 0;
2900                 command_p[0] = NULL;
2901                 parameters = NULL;
2902                 for (int i = 0; i <= strlen(cmd); i++)
2903                 {
2904                         cmd[i] = toupper(cmd[i]);
2905                 }
2906                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2907                 command = cmd;
2908         }
2909         else
2910         {
2911                 strcpy(cmd,"");
2912                 j = 0;
2913                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2914                 for (int i = 0; i < strlen(temp); i++)
2915                 {
2916                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2917                         {
2918                                 cmd[j++] = temp[i];
2919                                 cmd[j] = 0;
2920                         }
2921                 }
2922                 /* split the full string into a command plus parameters */
2923                 parameters = p;
2924                 strcpy(p," ");
2925                 command = cmd;
2926                 if (strchr(cmd,' '))
2927                 {
2928                         for (int i = 0; i <= strlen(cmd); i++)
2929                         {
2930                                 /* capitalise the command ONLY, leave params intact */
2931                                 cmd[i] = toupper(cmd[i]);
2932                                 /* are we nearly there yet?! :P */
2933                                 if (cmd[i] == ' ')
2934                                 {
2935                                         command = cmd;
2936                                         parameters = cmd+i+1;
2937                                         cmd[i] = '\0';
2938                                         break;
2939                                 }
2940                         }
2941                 }
2942                 else
2943                 {
2944                         for (int i = 0; i <= strlen(cmd); i++)
2945                         {
2946                                 cmd[i] = toupper(cmd[i]);
2947                         }
2948                 }
2949
2950         }
2951         cmd_found = 0;
2952         
2953         if (strlen(command)>MAXCOMMAND)
2954         {
2955                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
2956                 return;
2957         }
2958         
2959         for (int x = 0; x < strlen(command); x++)
2960         {
2961                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2962                 {
2963                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2964                         {
2965                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2966                                 {
2967                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2968                                         return;
2969                                 }
2970                         }
2971                 }
2972         }
2973
2974         for (int i = 0; i != cmdlist.size(); i++)
2975         {
2976                 if (strcmp(cmdlist[i].command,""))
2977                 {
2978                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2979                         {
2980                                 log(DEBUG,"Found matching command");
2981
2982                                 if (parameters)
2983                                 {
2984                                         if (strcmp(parameters,""))
2985                                         {
2986                                                 items = process_parameters(command_p,parameters);
2987                                         }
2988                                         else
2989                                         {
2990                                                 items = 0;
2991                                                 command_p[0] = NULL;
2992                                         }
2993                                 }
2994                                 else
2995                                 {
2996                                         items = 0;
2997                                         command_p[0] = NULL;
2998                                 }
2999                                 
3000                                 if (user)
3001                                 {
3002                                         log(DEBUG,"Processing command");
3003                                         
3004                                         /* activity resets the ping pending timer */
3005                                         user->nping = TIME + user->pingmax;
3006                                         if ((items) < cmdlist[i].min_params)
3007                                         {
3008                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
3009                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
3010                                                 return;
3011                                         }
3012                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
3013                                         {
3014                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3015                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
3016                                                 cmd_found = 1;
3017                                                 return;
3018                                         }
3019                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
3020                                         {
3021                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3022                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
3023                                                 cmd_found = 1;
3024                                                 return;
3025                                         }
3026                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
3027                                          * deny command! */
3028                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
3029                                         {
3030                                                 if ((!isnick(user->nick)) || (user->registered != 7))
3031                                                 {
3032                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3033                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
3034                                                         return;
3035                                                 }
3036                                         }
3037                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
3038                                         {
3039                                                 char* mycmd;
3040                                                 char* savept2;
3041                                                 mycmd = strtok_r(DisabledCommands," ",&savept2);
3042                                                 while (mycmd)
3043                                                 {
3044                                                         if (!strcasecmp(mycmd,command))
3045                                                         {
3046                                                                 // command is disabled!
3047                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
3048                                                                 return;
3049                                                         }
3050                                                         mycmd = strtok_r(NULL," ",&savept2);
3051                                                 }
3052         
3053
3054                                         }
3055                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
3056                                         {
3057                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
3058                                                 if (cmdlist[i].handler_function)
3059                                                 {
3060                                                         
3061                                                         /* ikky /stats counters */
3062                                                         if (temp)
3063                                                         {
3064                                                                 if (user)
3065                                                                 {
3066                                                                         user->bytes_in += strlen(temp);
3067                                                                         user->cmds_in++;
3068                                                                         user->bytes_out+=strlen(temp);
3069                                                                         user->cmds_out++;
3070                                                                 }
3071                                                                 cmdlist[i].use_count++;
3072                                                                 cmdlist[i].total_bytes+=strlen(temp);
3073                                                         }
3074
3075                                                         int MOD_RESULT = 0;
3076                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
3077                                                         if (MOD_RESULT == 1) {
3078                                                                 return;
3079                                                         }
3080
3081                                                         /* WARNING: nothing may come after the
3082                                                          * command handler call, as the handler
3083                                                          * may free the user structure! */
3084
3085                                                         cmdlist[i].handler_function(command_p,items,user);
3086                                                 }
3087                                                 return;
3088                                         }
3089                                         else
3090                                         {
3091                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3092                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
3093                                                 return;
3094                                         }
3095                                 }
3096                                 cmd_found = 1;
3097                         }
3098                 }
3099         }
3100         if ((!cmd_found) && (user))
3101         {
3102                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
3103                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3104         }
3105 }
3106
3107
3108 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
3109 {
3110         command_t comm;
3111         /* create the command and push it onto the table */     
3112         strlcpy(comm.command,cmd,MAXBUF);
3113         strlcpy(comm.source,source,MAXBUF);
3114         comm.handler_function = f;
3115         comm.flags_needed = flags;
3116         comm.min_params = minparams;
3117         comm.use_count = 0;
3118         comm.total_bytes = 0;
3119         cmdlist.push_back(comm);
3120         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
3121 }
3122
3123 bool removecommands(const char* source)
3124 {
3125         bool go_again = true;
3126         while (go_again)
3127         {
3128                 go_again = false;
3129                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
3130                 {
3131                         if (!strcmp(i->source,source))
3132                         {
3133                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
3134                                 cmdlist.erase(i);
3135                                 go_again = true;
3136                                 break;
3137                         }
3138                 }
3139         }
3140         return true;
3141 }
3142
3143 void SetupCommandTable(void)
3144 {
3145         createcommand("USER",handle_user,0,4,"<core>");
3146         createcommand("NICK",handle_nick,0,1,"<core>");
3147         createcommand("QUIT",handle_quit,0,0,"<core>");
3148         createcommand("VERSION",handle_version,0,0,"<core>");
3149         createcommand("PING",handle_ping,0,1,"<core>");
3150         createcommand("PONG",handle_pong,0,1,"<core>");
3151         createcommand("ADMIN",handle_admin,0,0,"<core>");
3152         createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
3153         createcommand("INFO",handle_info,0,0,"<core>");
3154         createcommand("TIME",handle_time,0,0,"<core>");
3155         createcommand("WHOIS",handle_whois,0,1,"<core>");
3156         createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
3157         createcommand("NOTICE",handle_notice,0,2,"<core>");
3158         createcommand("JOIN",handle_join,0,1,"<core>");
3159         createcommand("NAMES",handle_names,0,0,"<core>");
3160         createcommand("PART",handle_part,0,1,"<core>");
3161         createcommand("KICK",handle_kick,0,2,"<core>");
3162         createcommand("MODE",handle_mode,0,1,"<core>");
3163         createcommand("TOPIC",handle_topic,0,1,"<core>");
3164         createcommand("WHO",handle_who,0,1,"<core>");
3165         createcommand("MOTD",handle_motd,0,0,"<core>");
3166         createcommand("RULES",handle_rules,0,0,"<core>");
3167         createcommand("OPER",handle_oper,0,2,"<core>");
3168         createcommand("LIST",handle_list,0,0,"<core>");
3169         createcommand("DIE",handle_die,'o',1,"<core>");
3170         createcommand("RESTART",handle_restart,'o',1,"<core>");
3171         createcommand("KILL",handle_kill,'o',2,"<core>");
3172         createcommand("REHASH",handle_rehash,'o',0,"<core>");
3173         createcommand("LUSERS",handle_lusers,0,0,"<core>");
3174         createcommand("STATS",handle_stats,0,1,"<core>");
3175         createcommand("USERHOST",handle_userhost,0,1,"<core>");
3176         createcommand("AWAY",handle_away,0,0,"<core>");
3177         createcommand("ISON",handle_ison,0,0,"<core>");
3178         createcommand("SUMMON",handle_summon,0,0,"<core>");
3179         createcommand("USERS",handle_users,0,0,"<core>");
3180         createcommand("INVITE",handle_invite,0,2,"<core>");
3181         createcommand("PASS",handle_pass,0,1,"<core>");
3182         createcommand("TRACE",handle_trace,'o',0,"<core>");
3183         createcommand("WHOWAS",handle_whowas,0,1,"<core>");
3184         createcommand("CONNECT",handle_connect,'o',1,"<core>");
3185         createcommand("SQUIT",handle_squit,'o',0,"<core>");
3186         createcommand("MODULES",handle_modules,0,0,"<core>");
3187         createcommand("LINKS",handle_links,0,0,"<core>");
3188         createcommand("MAP",handle_map,0,0,"<core>");
3189         createcommand("KLINE",handle_kline,'o',1,"<core>");
3190         createcommand("GLINE",handle_gline,'o',1,"<core>");
3191         createcommand("ZLINE",handle_zline,'o',1,"<core>");
3192         createcommand("QLINE",handle_qline,'o',1,"<core>");
3193         createcommand("ELINE",handle_eline,'o',1,"<core>");
3194         createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
3195         createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
3196         createcommand("SERVER",handle_server,0,0,"<core>");
3197 }
3198
3199 void process_buffer(const char* cmdbuf,userrec *user)
3200 {
3201         if (!user)
3202         {
3203                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3204                 return;
3205         }
3206         char cmd[MAXBUF];
3207         int i;
3208         if (!cmdbuf)
3209         {
3210                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3211                 return;
3212         }
3213         if (!strcmp(cmdbuf,""))
3214         {
3215                 return;
3216         }
3217         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3218
3219         strlcpy(cmd,cmdbuf,MAXBUF);
3220         if (!strcmp(cmd,""))
3221         {
3222                 return;
3223         }
3224         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3225         {
3226                 cmd[strlen(cmd)-1] = '\0';
3227         }
3228         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3229         {
3230                 cmd[strlen(cmd)-1] = '\0';
3231         }
3232
3233         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3234         {
3235                 cmd[strlen(cmd)-1] = '\0';
3236         }
3237
3238         if (!strcmp(cmd,""))
3239         {
3240                 return;
3241         }
3242         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3243         tidystring(cmd);
3244         if ((user) && (cmd))
3245         {
3246                 process_command(user,cmd);
3247         }
3248 }
3249
3250 void DoSync(serverrec* serv, char* tcp_host)
3251 {
3252         char data[MAXBUF];
3253         log(DEBUG,"Sending sync");
3254         // send start of sync marker: Y <timestamp>
3255         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3256         // except the ones its receiving it from.
3257         snprintf(data,MAXBUF,"Y %d",TIME);
3258         serv->SendPacket(data,tcp_host);
3259         // send users and channels
3260         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3261         {
3262                 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);
3263                 serv->SendPacket(data,tcp_host);
3264                 if (strchr(u->second->modes,'o'))
3265                 {
3266                         snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3267                         serv->SendPacket(data,tcp_host);
3268                 }
3269                 for (int i = 0; i <= MODCOUNT; i++)
3270                 {
3271                         string_list l = modules[i]->OnUserSync(u->second);
3272                         for (int j = 0; j < l.size(); j++)
3273                         {
3274                                 strlcpy(data,l[j].c_str(),MAXBUF);
3275                                 serv->SendPacket(data,tcp_host);
3276                         }
3277                 }
3278                 if (strcmp(chlist(u->second),""))
3279                 {
3280                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3281                         serv->SendPacket(data,tcp_host);
3282                 }
3283         }
3284         // send channel modes, topics etc...
3285         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3286         {
3287                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3288                 serv->SendPacket(data,tcp_host);
3289                 for (int i = 0; i <= MODCOUNT; i++)
3290                 {
3291                         string_list l = modules[i]->OnChannelSync(c->second);
3292                         for (int j = 0; j < l.size(); j++)
3293                         {
3294                                 strlcpy(data,l[j].c_str(),MAXBUF);
3295                                 serv->SendPacket(data,tcp_host);
3296                         }
3297                 }
3298                 if (strcmp(c->second->topic,""))
3299                 {
3300                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3301                         serv->SendPacket(data,tcp_host);
3302                 }
3303                 // send current banlist
3304                 
3305                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3306                 {
3307                         snprintf(data,MAXBUF,"M %s +b %s",c->second->name,b->data);
3308                         serv->SendPacket(data,tcp_host);
3309                 }
3310         }
3311         // sync global zlines, glines, etc
3312         sync_xlines(serv,tcp_host);
3313
3314         for (int j = 0; j < 32; j++)
3315         {
3316                 if (me[j] != NULL)
3317                 {
3318                         for (int k = 0; k < me[j]->connectors.size(); k++)
3319                         {
3320                                 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3321                                 {
3322                                         snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3323                                         serv->SendPacket(data,tcp_host);
3324                                         NetSendMyRoutingTable();
3325                                 }
3326                         }
3327                 }
3328         }
3329
3330         snprintf(data,MAXBUF,"F %d",TIME);
3331         serv->SendPacket(data,tcp_host);
3332         log(DEBUG,"Sent sync");
3333         // ircd sends its serverlist after the end of sync here
3334 }
3335
3336
3337 void NetSendMyRoutingTable()
3338 {
3339         // send out a line saying what is reachable to us.
3340         // E.g. if A is linked to B C and D, send out:
3341         // $ A B C D
3342         // if its only linked to B and D send out:
3343         // $ A B D
3344         // if it has no links, dont even send out the line at all.
3345         char buffer[MAXBUF];
3346         snprintf(buffer,MAXBUF,"$ %s",ServerName);
3347         bool sendit = false;
3348         for (int i = 0; i < 32; i++)
3349         {
3350                 if (me[i] != NULL)
3351                 {
3352                         for (int j = 0; j < me[i]->connectors.size(); j++)
3353                         {
3354                                 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3355                                 {
3356                                         strlcat(buffer," ",MAXBUF);
3357                                         strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3358                                         sendit = true;
3359                                 }
3360                         }
3361                 }
3362         }
3363         if (sendit)
3364                 NetSendToAll(buffer);
3365 }
3366
3367
3368 void DoSplit(const char* params)
3369 {
3370         bool go_again = true;
3371         while (go_again)
3372         {
3373                 go_again = false;
3374                 for (int i = 0; i < 32; i++)
3375                 {
3376                         if (me[i] != NULL)
3377                         {
3378                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3379                                 {
3380                                         if (!strcasecmp(j->GetServerName().c_str(),params))
3381                                         {
3382                                                 j->routes.clear();
3383                                                 j->CloseConnection();
3384                                                 me[i]->connectors.erase(j);
3385                                                 go_again = true;
3386                                                 break;
3387                                         }
3388                                 }
3389                         }
3390                 }
3391         }
3392         log(DEBUG,"Removed server. Will remove clients...");
3393         // iterate through the userlist and remove all users on this server.
3394         // because we're dealing with a mesh, we dont have to deal with anything
3395         // "down-route" from this server (nice huh)
3396         go_again = true;
3397         char reason[MAXBUF];
3398         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3399         while (go_again)
3400         {
3401                 go_again = false;
3402                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3403                 {
3404                         if (!strcasecmp(u->second->server,params))
3405                         {
3406                                 kill_link(u->second,reason);
3407                                 go_again = true;
3408                                 break;
3409                         }
3410                 }
3411         }
3412 }
3413
3414 // removes a server. Will NOT remove its users!
3415
3416 void RemoveServer(const char* name)
3417 {
3418         bool go_again = true;
3419         while (go_again)
3420         {
3421                 go_again = false;
3422                 for (int i = 0; i < 32; i++)
3423                 {
3424                         if (me[i] != NULL)
3425                         {
3426                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3427                                 {
3428                                         if (!strcasecmp(j->GetServerName().c_str(),name))
3429                                         {
3430                                                 j->routes.clear();
3431                                                 j->CloseConnection();
3432                                                 me[i]->connectors.erase(j);
3433                                                 go_again = true;
3434                                                 break;
3435                                         }
3436                                 }
3437                         }
3438                 }
3439         }
3440 }
3441
3442
3443 int reap_counter = 0;
3444 char MODERR[MAXBUF];
3445
3446 char* ModuleError()
3447 {
3448         return MODERR;
3449 }
3450
3451 void erase_factory(int j)
3452 {
3453         int v = 0;
3454         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
3455         {
3456                 if (v == j)
3457                 {
3458                         factory.erase(t);
3459                         factory.push_back(NULL);
3460                         return;
3461                 }
3462                 v++;
3463         }
3464 }
3465
3466 void erase_module(int j)
3467 {
3468         int v = 0;
3469         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
3470         {
3471                 if (v == j)
3472                 {
3473                         delete *m;
3474                         modules.erase(m);
3475                         modules.push_back(NULL);
3476                         break;
3477                 }
3478                 v++;
3479         }
3480         int v2 = 0;
3481         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
3482         {
3483                 if (v2 == j)
3484                 {
3485                        module_names.erase(v);
3486                        break;
3487                 }
3488                 v2++;
3489         }
3490
3491 }
3492
3493 bool UnloadModule(const char* filename)
3494 {
3495         for (int j = 0; j != module_names.size(); j++)
3496         {
3497                 if (module_names[j] == std::string(filename))
3498                 {
3499                         if (modules[j]->GetVersion().Flags & VF_STATIC)
3500                         {
3501                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
3502                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
3503                                 return false;
3504                         }
3505                         // found the module
3506                         log(DEBUG,"Deleting module...");
3507                         erase_module(j);
3508                         log(DEBUG,"Erasing module entry...");
3509                         erase_factory(j);
3510                         log(DEBUG,"Removing dependent commands...");
3511                         removecommands(filename);
3512                         log(DEFAULT,"Module %s unloaded",filename);
3513                         MODCOUNT--;
3514                         return true;
3515                 }
3516         }
3517         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
3518         snprintf(MODERR,MAXBUF,"Module not loaded");
3519         return false;
3520 }
3521
3522 bool DirValid(char* dirandfile)
3523 {
3524         char work[MAXBUF];
3525         strlcpy(work,dirandfile,MAXBUF);
3526         int p = strlen(work);
3527         // we just want the dir
3528         while (strlen(work))
3529         {
3530                 if (work[p] == '/')
3531                 {
3532                         work[p] = '\0';
3533                         break;
3534                 }
3535                 work[p--] = '\0';
3536         }
3537         log(DEBUG,"Dir valid: %s",work);
3538         char buffer[MAXBUF], otherdir[MAXBUF];
3539         // Get the current working directory
3540         if( getcwd( buffer, MAXBUF ) == NULL )
3541                 return false;
3542         chdir(work);
3543         if( getcwd( otherdir, MAXBUF ) == NULL )
3544                 return false;
3545         chdir(buffer);
3546         log(DEBUG,"Dir is really: %s",otherdir);
3547         if (strlen(otherdir) >= strlen(work))
3548         {
3549                 otherdir[strlen(work)] = '\0';
3550                 log(DEBUG,"Compare: '%s' -> '%s'",otherdir,work);
3551                 if (!strcmp(otherdir,work))
3552                 {
3553                         log(DEBUG,"Match ok");
3554                         return true;
3555                 }
3556                 log(DEBUG,"No match");
3557                 return false;
3558         }
3559         else return false;
3560 }
3561
3562 bool LoadModule(const char* filename)
3563 {
3564         char modfile[MAXBUF];
3565         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
3566         if (!DirValid(modfile))
3567         {
3568                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
3569                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
3570                 return false;
3571         }
3572         log(DEBUG,"Loading module: %s",modfile);
3573         if (FileExists(modfile))
3574         {
3575                 for (int j = 0; j < module_names.size(); j++)
3576                 {
3577                         if (module_names[j] == std::string(filename))
3578                         {
3579                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
3580                                 snprintf(MODERR,MAXBUF,"Module already loaded");
3581                                 return false;
3582                         }
3583                 }
3584                 ircd_module* a = new ircd_module(modfile);
3585                 factory[MODCOUNT+1] = a;
3586                 if (factory[MODCOUNT+1]->LastError())
3587                 {
3588                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
3589                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
3590                         MODCOUNT--;
3591                         return false;
3592                 }
3593                 if (factory[MODCOUNT+1]->factory)
3594                 {
3595                         Module* m = factory[MODCOUNT+1]->factory->CreateModule();
3596                         modules[MODCOUNT+1] = m;
3597                         /* save the module and the module's classfactory, if
3598                          * this isnt done, random crashes can occur :/ */
3599                         module_names.push_back(filename);
3600                 }
3601                 else
3602                 {
3603                         log(DEFAULT,"Unable to load %s",modfile);
3604                         snprintf(MODERR,MAXBUF,"Factory function failed!");
3605                         return false;
3606                 }
3607         }
3608         else
3609         {
3610                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
3611                 snprintf(MODERR,MAXBUF,"Module file could not be found");
3612                 return false;
3613         }
3614         MODCOUNT++;
3615         return true;
3616 }
3617
3618 int InspIRCd(void)
3619 {
3620         struct sockaddr_in client,server;
3621         char addrs[MAXBUF][255];
3622         int incomingSockfd, result = TRUE;
3623         socklen_t length;
3624         int count = 0;
3625         int selectResult = 0, selectResult2 = 0;
3626         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3627         char resolvedHost[MAXBUF];
3628         fd_set selectFds;
3629         timeval tv;
3630
3631         log_file = fopen("ircd.log","a+");
3632         if (!log_file)
3633         {
3634                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3635                 Exit(ERROR);
3636         }
3637
3638         log(DEBUG,"InspIRCd: startup: begin");
3639         log(DEBUG,"$Id$");
3640         if (geteuid() == 0)
3641         {
3642                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3643                 Exit(ERROR);
3644                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
3645         }
3646         SetupCommandTable();
3647         log(DEBUG,"InspIRCd: startup: default command table set up");
3648         
3649         ReadConfig(true,NULL);
3650         if (strcmp(DieValue,"")) 
3651         { 
3652                 printf("WARNING: %s\n\n",DieValue);
3653                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3654                 exit(0); 
3655         }  
3656         log(DEBUG,"InspIRCd: startup: read config");
3657           
3658         int count2 = 0, count3 = 0;
3659
3660         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3661         {
3662                 ConfValue("bind","port",count,configToken,&config_f);
3663                 ConfValue("bind","address",count,Addr,&config_f);
3664                 ConfValue("bind","type",count,Type,&config_f);
3665                 if (!strcmp(Type,"servers"))
3666                 {
3667                         char Default[MAXBUF];
3668                         strcpy(Default,"no");
3669                         ConfValue("bind","default",count,Default,&config_f);
3670                         if (strchr(Default,'y'))
3671                         {
3672                                 defaultRoute = count3;
3673                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3674                         }
3675                         me[count3] = new serverrec(ServerName,100L,false);
3676                         if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3677                         {
3678                                 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3679                         }
3680                         else
3681                         {
3682                                 count3++;
3683                         }
3684                 }
3685                 else
3686                 {
3687                         ports[count2] = atoi(configToken);
3688                         strlcpy(addrs[count2],Addr,256);
3689                         count2++;
3690                 }
3691                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3692         }
3693         portCount = count2;
3694         UDPportCount = count3;
3695           
3696         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3697         
3698         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3699         
3700         printf("\n");
3701         
3702         /* BugFix By Craig! :p */
3703         MODCOUNT = -1;
3704         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3705         {
3706                 ConfValue("module","name",count2,configToken,&config_f);
3707                 printf("Loading module... \033[1;37m%s\033[0;37m\n",configToken);
3708                 if (!LoadModule(configToken))
3709                 {
3710                         log(DEBUG,"Exiting due to a module loader error.");
3711                         printf("There was an error loading a module: %s\n",ModuleError());
3712                         Exit(0);
3713                 }
3714         }
3715         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3716         
3717         printf("\nInspIRCd is now running!\n");
3718         
3719         startup_time = time(NULL);
3720           
3721         if (nofork)
3722         {
3723                 log(VERBOSE,"Not forking as -nofork was specified");
3724         }
3725         else
3726         {
3727                 if (DaemonSeed() == ERROR)
3728                 {
3729                         log(DEFAULT,"InspIRCd: startup: can't daemonise");
3730                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3731                         Exit(ERROR);
3732                 }
3733         }
3734
3735         char PID[MAXBUF];
3736         ConfValue("pid","file",0,PID,&config_f);
3737         WritePID(PID);
3738           
3739           
3740         /* setup select call */
3741         FD_ZERO(&selectFds);
3742         log(DEBUG,"InspIRCd: startup: zero selects");
3743         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3744         
3745         for (count = 0; count < portCount; count++)
3746         {
3747                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3748                 {
3749                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3750                         return(ERROR);
3751                 }
3752                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3753                 {
3754                         log(DEFAULT,"InspIRCd: startup: failed to bind port %d",ports[count]);
3755                 }
3756                 else    /* well we at least bound to one socket so we'll continue */
3757                 {
3758                         boundPortCount++;
3759                 }
3760         }
3761         
3762         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3763           
3764         /* if we didn't bind to anything then abort */
3765         if (boundPortCount == 0)
3766         {
3767                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
3768                 return (ERROR);
3769         }
3770         
3771
3772         length = sizeof (client);
3773         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3774
3775         fd_set serverfds;
3776         timeval tvs;
3777         tvs.tv_usec = 7000L;
3778         tvs.tv_sec = 0;
3779         tv.tv_sec = 0;
3780         tv.tv_usec = 7000L;
3781         char data[10240];
3782         timeval tval;
3783         fd_set sfd;
3784         tval.tv_usec = 7000L;
3785         tval.tv_sec = 0;
3786         int total_in_this_set = 0;
3787         int v = 0;
3788         bool expire_run = false;
3789           
3790         /* main loop, this never returns */
3791         for (;;)
3792         {
3793 #ifdef _POSIX_PRIORITY_SCHEDULING
3794                 sched_yield();
3795 #endif
3796                 // poll dns queue
3797                 dns_poll();
3798                 FD_ZERO(&sfd);
3799
3800                 // we only read time() once per iteration rather than tons of times!
3801                 TIME = time(NULL);
3802
3803                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3804                 // them in a list, then reap the list every second or so.
3805                 if (((TIME % 5) == 0) && (!expire_run))
3806                 {
3807                         expire_lines();
3808                         FOREACH_MOD OnBackgroundTimer(TIME);
3809                         expire_run = true;
3810                         continue;
3811                 }
3812                 if ((TIME % 5) == 1)
3813                         expire_run = false;
3814                 if (reap_counter>300)
3815                 {
3816                         if (fd_reap.size() > 0)
3817                         {
3818                                 for( int n = 0; n < fd_reap.size(); n++)
3819                                 {
3820                                         if ((fd_reap[n] > -1))
3821                                         {
3822                                                 close(fd_reap[n]);
3823                                                 shutdown (fd_reap[n],2);
3824                                         }
3825                                 }
3826                         }
3827                         fd_reap.clear();
3828                         reap_counter=0;
3829                 }
3830                 reap_counter++;
3831                 
3832                 // fix by brain - this must be below any manipulation of the hashmap by modules
3833                 user_hash::iterator count2 = clientlist.begin();
3834
3835                 FD_ZERO(&serverfds);
3836                 
3837                 for (int x = 0; x != UDPportCount; x++)
3838                 {
3839                         if (me[x])
3840                                 FD_SET(me[x]->fd, &serverfds);
3841                 }
3842                 
3843                 // serverFds timevals went here
3844                 
3845                 tvs.tv_usec = 7000L;
3846                 tvs.tv_sec = 0;
3847                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3848                 if (servresult > 0)
3849                 {
3850                         for (int x = 0; x != UDPportCount; x++)
3851                         {
3852                                 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3853                                 {
3854                                         char remotehost[MAXBUF],resolved[MAXBUF];
3855                                         length = sizeof (client);
3856                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3857                                         if (incomingSockfd != -1)
3858                                         {
3859                                                 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3860                                                 if(CleanAndResolve(resolved, remotehost) != TRUE)
3861                                                 {
3862                                                         strlcpy(resolved,remotehost,MAXBUF);
3863                                                 }
3864                                                 // add to this connections ircd_connector vector
3865                                                 // *FIX* - we need the LOCAL port not the remote port in &client!
3866                                                 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3867                                         }
3868                                 }
3869                         }
3870                 }
3871      
3872                 for (int x = 0; x < UDPportCount; x++)
3873                 {
3874                         std::deque<std::string> msgs;
3875                         msgs.clear();
3876                         if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3877                         {
3878                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
3879                                 {
3880                                         char udp_msg[MAXBUF];
3881                                         strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3882                                         log(DEBUG,"Processing: %s",udp_msg);
3883                                         if (strlen(udp_msg)<1)
3884                                         {
3885                                                 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3886                                                 break;
3887                                         }
3888                                         // during a netburst, send all data to all other linked servers
3889                                         if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3890                                         {
3891                                                 if (is_uline(tcp_host))
3892                                                 {
3893                                                         if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3894                                                         {
3895                                                                 NetSendToAllExcept(tcp_host,udp_msg);
3896                                                         }
3897                                                 }
3898                                                 else
3899                                                         NetSendToAllExcept(tcp_host,udp_msg);
3900                                         }
3901                                         std::string msg = udp_msg;
3902                                         FOREACH_MOD OnPacketReceive(msg,tcp_host);
3903                                         strlcpy(udp_msg,msg.c_str(),MAXBUF);
3904                                         handle_link_packet(udp_msg, tcp_host, me[x]);
3905                                 }
3906                                 goto label;
3907                         }
3908                 }
3909         
3910
3911         while (count2 != clientlist.end())
3912         {
3913                 FD_ZERO(&sfd);
3914                 total_in_this_set = 0;
3915
3916                 user_hash::iterator xcount = count2;
3917                 user_hash::iterator endingiter = count2;
3918
3919                 if (count2 == clientlist.end()) break;
3920
3921                 if (count2->second)
3922                 if (count2->second->fd != 0)
3923                 {
3924                         // assemble up to 64 sockets into an fd_set
3925                         // to implement a pooling mechanism.
3926                         //
3927                         // This should be up to 64x faster than the
3928                         // old implementation.
3929                         while (total_in_this_set < 64)
3930                         {
3931                                 if (count2 != clientlist.end())
3932                                 {
3933                                         // we don't check the state of remote users.
3934                                         if ((count2->second->fd != -1) && (count2->second->fd != FD_MAGIC_NUMBER))
3935                                         {
3936                                                 FD_SET (count2->second->fd, &sfd);
3937
3938                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3939                                                 // their connection class.
3940                                                 if ((TIME > count2->second->timeout) && (count2->second->registered != 7)) 
3941                                                 {
3942                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3943                                                         kill_link(count2->second,"Registration timeout");
3944                                                         goto label;
3945                                                 }
3946                                                 if ((TIME > count2->second->signon) && (count2->second->registered == 3) && (AllModulesReportReady(count2->second)))
3947                                                 {
3948                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3949                                                         count2->second->dns_done = true;
3950                                                         FullConnectUser(count2->second);
3951                                                         goto label;
3952                                                 }
3953                                                 if ((count2->second->dns_done) && (count2->second->registered == 3) && (AllModulesReportReady(count2->second))) // both NICK and USER... and DNS
3954                                                 {
3955                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
3956                                                         FullConnectUser(count2->second);
3957                                                         goto label;
3958                                                 }
3959                                                 if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3960                                                 {
3961                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
3962                                                         {
3963                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3964                                                                 kill_link(count2->second,"Ping timeout");
3965                                                                 goto label;
3966                                                         }
3967                                                         Write(count2->second->fd,"PING :%s",ServerName);
3968                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3969                                                         count2->second->lastping = 0;
3970                                                         count2->second->nping = TIME+count2->second->pingmax;   // was hard coded to 120
3971                                                 }
3972                                         }
3973                                         count2++;
3974                                         total_in_this_set++;
3975                                 }
3976                                 else break;
3977                         }
3978    
3979                         endingiter = count2;
3980                         count2 = xcount; // roll back to where we were
3981         
3982                         v = 0;
3983
3984                         // tvals defined here
3985
3986                         tval.tv_usec = 7000L;
3987                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3988                         
3989                         // now loop through all of the items in this pool if any are waiting
3990                         //if (selectResult2 > 0)
3991                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3992                         {
3993
3994 #ifdef _POSIX_PRIORITY_SCHEDULING
3995                                 sched_yield();
3996 #endif
3997
3998                                 result = EAGAIN;
3999                                 if ((count2a->second->fd != FD_MAGIC_NUMBER) && (count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
4000                                 {
4001                                         memset(data, 0, 10240);
4002                                         result = read(count2a->second->fd, data, 10240);
4003                                         
4004                                         if (result)
4005                                         {
4006                                                 // perform a check on the raw buffer as an array (not a string!) to remove
4007                                                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
4008                                                 // hopefully this should stop even more people whining about "Unknown command: *"
4009                                                 for (int checker = 0; checker < result; checker++)
4010                                                 {
4011                                                         if ((data[checker] == 0) || (data[checker] == 7))
4012                                                                 data[checker] = ' ';
4013                                                 }
4014                                                 userrec* current = count2a->second;
4015                                                 int currfd = current->fd;
4016                                                 char* l = strtok(data,"\n");
4017                                                 int floodlines = 0;
4018                                                 while (l)
4019                                                 {
4020                                                         floodlines++;
4021                                                         if ((floodlines > current->flood) && (current->flood != 0))
4022                                                         {
4023                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4024                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4025                                                                 kill_link(current,"Excess flood");
4026                                                                 goto label;
4027                                                         }
4028                                                         char sanitized[NetBufferSize];
4029                                                         memset(sanitized, 0, NetBufferSize);
4030                                                         int ptt = 0;
4031                                                         for (int pt = 0; pt < strlen(l); pt++)
4032                                                         {
4033                                                                 if (l[pt] != '\r')
4034                                                                 {
4035                                                                         sanitized[ptt++] = l[pt];
4036                                                                 }
4037                                                         }
4038                                                         sanitized[ptt] = '\0';
4039                                                         if (strlen(sanitized))
4040                                                         {
4041
4042
4043                                                                 // we're gonna re-scan to check if the nick is gone, after every
4044                                                                 // command - if it has, we're gonna bail
4045                                                                 bool find_again = false;
4046                                                                 process_buffer(sanitized,current);
4047         
4048                                                                 // look for the user's record in case it's changed
4049                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
4050                                                                 {
4051                                                                         if (c2->second->fd == currfd)
4052                                                                         {
4053                                                                                 // found again, update pointer
4054                                                                                 current == c2->second;
4055                                                                                 find_again = true;
4056                                                                                 break;
4057                                                                         }
4058                                                                 }
4059                                                                 if (!find_again)
4060                                                                         goto label;
4061
4062                                                         }
4063                                                         l = strtok(NULL,"\n");
4064                                                 }
4065                                                 goto label;
4066                                         }
4067
4068                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
4069                                         {
4070                                                 log(DEBUG,"killing: %s",count2a->second->nick);
4071                                                 kill_link(count2a->second,strerror(errno));
4072                                                 goto label;
4073                                         }
4074                                 }
4075                                 // result EAGAIN means nothing read
4076                                 if (result == EAGAIN)
4077                                 {
4078                                 }
4079                                 else
4080                                 if (result == 0)
4081                                 {
4082                                         if (count2->second)
4083                                         {
4084                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
4085                                                 kill_link(count2a->second,"Client exited");
4086                                                 // must bail here? kill_link removes the hash, corrupting the iterator
4087                                                 log(DEBUG,"Bailing from client exit");
4088                                                 goto label;
4089                                         }
4090                                 }
4091                                 else if (result > 0)
4092                                 {
4093                                 }
4094                         }
4095                 }
4096                 for (int q = 0; q < total_in_this_set; q++)
4097                 {
4098                         // there is no iterator += operator :(
4099                         //if (count2 != clientlist.end())
4100                         //{
4101                                 count2++;
4102                         //}
4103                 }
4104         }
4105         
4106         // set up select call
4107         for (count = 0; count < boundPortCount; count++)
4108         {
4109                 FD_SET (openSockfd[count], &selectFds);
4110         }
4111
4112         tv.tv_usec = 7000L;
4113         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4114
4115         /* select is reporting a waiting socket. Poll them all to find out which */
4116         if (selectResult > 0)
4117         {
4118                 char target[MAXBUF], resolved[MAXBUF];
4119                 for (count = 0; count < boundPortCount; count++)                
4120                 {
4121                         if (FD_ISSET (openSockfd[count], &selectFds))
4122                         {
4123                                 length = sizeof (client);
4124                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4125                               
4126                                 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4127                                 strlcpy (resolved, target, MAXBUF);
4128                         
4129                                 if (incomingSockfd < 0)
4130                                 {
4131                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4132                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4133                                 }
4134                                 else
4135                                 {
4136                                         AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
4137                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4138                                 }
4139                                 goto label;
4140                         }
4141                 }
4142         }
4143         label:
4144         if (0) {};
4145 }
4146 /* not reached */
4147 close (incomingSockfd);
4148 }
4149