]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Started moving of data into ServerConfig class
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 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_config.h"
22 #include "inspircd.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.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 <time.h>
31 #include <string>
32 #ifdef GCC3
33 #include <ext/hash_map>
34 #else
35 #include <hash_map>
36 #endif
37 #include <map>
38 #include <sstream>
39 #include <vector>
40 #include <deque>
41 #include <sched.h>
42 #ifdef THREADED_DNS
43 #include <pthread.h>
44 #endif
45 #include "users.h"
46 #include "ctables.h"
47 #include "globals.h"
48 #include "modules.h"
49 #include "dynamic.h"
50 #include "wildcard.h"
51 #include "message.h"
52 #include "mode.h"
53 #include "commands.h"
54 #include "xline.h"
55 #include "inspstring.h"
56 #include "dnsqueue.h"
57 #include "helperfuncs.h"
58 #include "hashcomp.h"
59 #include "socketengine.h"
60 #include "userprocess.h"
61 #include "socket.h"
62 #include "dns.h"
63
64 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
65 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
66 int DieDelay  =  5;
67 time_t startup_time = time(NULL);
68
69 extern std::vector<Module*> modules;
70 std::vector<std::string> module_names;
71 extern std::vector<ircd_module*> factory;
72
73 std::vector<InspSocket*> module_sockets;
74
75 extern int MODCOUNT;
76 int openSockfd[MAXSOCKS];
77 struct sockaddr_in client,server;
78 socklen_t length;
79
80 extern InspSocket* socket_ref[65535];
81
82 time_t TIME = time(NULL), OLDTIME = time(NULL);
83
84 SocketEngine* SE = NULL;
85
86 extern std::vector<std::string> include_stack;
87
88 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
89 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
90 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
91 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
92 typedef std::deque<command_t> command_table;
93 typedef std::vector<std::string> servernamelist;
94
95 // This table references users by file descriptor.
96 // its an array to make it VERY fast, as all lookups are referenced
97 // by an integer, meaning there is no need for a scan/search operation.
98 userrec* fd_ref_table[65536];
99
100 serverstats* stats = new serverstats;
101 Server* MyServer = new Server;
102 ServerConfig *Config = new ServerConfig;
103
104 user_hash clientlist;
105 chan_hash chanlist;
106 whowas_hash whowas;
107 command_table cmdlist;
108 autoconnects autoconns;
109 file_cache MOTD;
110 file_cache RULES;
111 address_cache IP;
112
113 ClassVector Classes;
114 servernamelist servernames;
115
116 int boundPortCount = 0;
117 int portCount = 0, ports[MAXSOCKS];
118
119 /* prototypes */
120
121 int has_channel(userrec *u, chanrec *c);
122 int usercount(chanrec *c);
123 int usercount_i(chanrec *c);
124 char* Passwd(userrec *user);
125 bool IsDenied(userrec *user);
126 void AddWhoWas(userrec* u);
127
128 std::stringstream config_f(stringstream::in | stringstream::out);
129
130 std::vector<userrec*> all_opers;
131
132 char lowermap[255];
133
134 void AddOper(userrec* user)
135 {
136         log(DEBUG,"Oper added to optimization list");
137         all_opers.push_back(user);
138 }
139
140 void AddServerName(std::string servername)
141 {
142         log(DEBUG,"Adding server name: %s",servername.c_str());
143         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
144         {
145                 if (*a == servername)
146                         return;
147         }
148         servernames.push_back(servername);
149 }
150
151 const char* FindServerNamePtr(std::string servername)
152 {
153         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
154         {
155                 if (*a == servername)
156                         return a->c_str();
157         }
158         AddServerName(servername);
159         return FindServerNamePtr(servername);
160 }
161
162 void DeleteOper(userrec* user)
163 {
164         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
165         {
166                 if (*a == user)
167                 {
168                         log(DEBUG,"Oper removed from optimization list");
169                         all_opers.erase(a);
170                         return;
171                 }
172         }
173 }
174
175 std::string GetRevision()
176 {
177         /* w00t got me to replace a bunch of strtok_r
178          * with something nicer, so i did this. Its the
179          * same thing really, only in C++. It places the
180          * text into a std::stringstream which is a readable
181          * and writeable buffer stream, and then pops two
182          * words off it, space delimited. Because it reads
183          * into the same variable twice, the first word
184          * is discarded, and the second one returned.
185          */
186         std::stringstream Revision("$Revision$");
187         std::string single;
188         Revision >> single >> single;
189         return single;
190 }
191
192
193 std::string getservername()
194 {
195         return Config->ServerName;
196 }
197
198 std::string getserverdesc()
199 {
200         return Config->ServerDesc;
201 }
202
203 std::string getnetworkname()
204 {
205         return Config->Network;
206 }
207
208 std::string getadminname()
209 {
210         return Config->AdminName;
211 }
212
213 std::string getadminemail()
214 {
215         return Config->AdminEmail;
216 }
217
218 std::string getadminnick()
219 {
220         return Config->AdminNick;
221 }
222
223 void ReadConfig(bool bail, userrec* user)
224 {
225         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
226         char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
227         ConnectClass c;
228         std::stringstream errstr;
229         include_stack.clear();
230         
231         if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
232         {
233                 errstr.seekg(0);
234                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
235                 if (bail)
236                 {
237                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
238                         Exit(0);
239                 }
240                 else
241                 {
242                         char dataline[1024];
243                         if (user)
244                         {
245                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
246                                 while (!errstr.eof())
247                                 {
248                                         errstr.getline(dataline,1024);
249                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
250                                 }
251                         }
252                         else
253                         {
254                                 WriteOpers("There were errors in the configuration file:");
255                                 while (!errstr.eof())
256                                 {
257                                         errstr.getline(dataline,1024);
258                                         WriteOpers(dataline);
259                                 }
260                         }
261                         return;
262                 }
263         }
264           
265         ConfValue("server","name",0,Config->ServerName,&config_f);
266         ConfValue("server","description",0,Config->ServerDesc,&config_f);
267         ConfValue("server","network",0,Config->Network,&config_f);
268         ConfValue("admin","name",0,Config->AdminName,&config_f);
269         ConfValue("admin","email",0,Config->AdminEmail,&config_f);
270         ConfValue("admin","nick",0,Config->AdminNick,&config_f);
271         ConfValue("files","motd",0,Config->motd,&config_f);
272         ConfValue("files","rules",0,Config->rules,&config_f);
273         ConfValue("power","diepass",0,Config->diepass,&config_f);
274         ConfValue("power","pause",0,pauseval,&config_f);
275         ConfValue("power","restartpass",0,Config->restartpass,&config_f);
276         ConfValue("options","prefixquit",0,Config->PrefixQuit,&config_f);
277         ConfValue("die","value",0,Config->DieValue,&config_f);
278         ConfValue("options","loglevel",0,dbg,&config_f);
279         ConfValue("options","netbuffersize",0,NB,&config_f);
280         ConfValue("options","maxwho",0,MW,&config_f);
281         ConfValue("options","allowhalfop",0,AH,&config_f);
282         ConfValue("options","allowprotect",0,AP,&config_f);
283         ConfValue("options","allowfounder",0,AF,&config_f);
284         ConfValue("dns","server",0,Config->DNSServer,&config_f);
285         ConfValue("dns","timeout",0,DNT,&config_f);
286         ConfValue("options","moduledir",0,Config->ModPath,&config_f);
287         ConfValue("disabled","commands",0,Config->DisabledCommands,&config_f);
288         ConfValue("options","somaxconn",0,MCON,&config_f);
289         ConfValue("options","softlimit",0,SLIMT,&config_f);
290
291         Config->SoftLimit = atoi(SLIMT);
292         if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
293         {
294                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
295                 Config->SoftLimit = MAXCLIENTS;
296         }
297         Config->MaxConn = atoi(MCON);
298         if (MaxConn > SOMAXCONN)
299                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
300         Config->NetBufferSize = atoi(NB);
301         Config->MaxWhoResults = atoi(MW);
302         Config->dns_timeout = atoi(DNT);
303         if (!Config->dns_timeout)
304                 Config->dns_timeout = 5;
305         if (!Config->MaxConn)
306                 Config->MaxConn = SOMAXCONN;
307         if (!*Config->DNSServer)
308                 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
309         if (!*Config->ModPath)
310                 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
311         Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
312         if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
313         {
314                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
315                 Config->NetBufferSize = 10240;
316         }
317         if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
318         {
319                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
320                 Config->MaxWhoResults = 128;
321         }
322         if (!strcmp(dbg,"debug"))
323         {
324                 Config->LogLevel = DEBUG;
325                 Config->debugging = 1;
326         }
327         if (!strcmp(dbg,"verbose"))
328                 Config->LogLevel = VERBOSE;
329         if (!strcmp(dbg,"default"))
330                 Config->LogLevel = DEFAULT;
331         if (!strcmp(dbg,"sparse"))
332                 Config->LogLevel = SPARSE;
333         if (!strcmp(dbg,"none"))
334                 Config->LogLevel = NONE;
335         readfile(MOTD,Config->motd);
336         log(DEFAULT,"Reading message of the day...");
337         readfile(RULES,Config->rules);
338         log(DEFAULT,"Reading connect classes...");
339         Classes.clear();
340         for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
341         {
342                 strcpy(Value,"");
343                 ConfValue("connect","allow",i,Value,&config_f);
344                 ConfValue("connect","timeout",i,timeout,&config_f);
345                 ConfValue("connect","flood",i,flood,&config_f);
346                 ConfValue("connect","pingfreq",i,pfreq,&config_f);
347                 ConfValue("connect","threshold",i,thold,&config_f);
348                 ConfValue("connect","sendq",i,sqmax,&config_f);
349                 ConfValue("connect","recvq",i,rqmax,&config_f);
350                 if (Value[0])
351                 {
352                         strlcpy(c.host,Value,MAXBUF);
353                         c.type = CC_ALLOW;
354                         strlcpy(Value,"",MAXBUF);
355                         ConfValue("connect","password",i,Value,&config_f);
356                         strlcpy(c.pass,Value,MAXBUF);
357                         c.registration_timeout = 90; // default is 2 minutes
358                         c.pingtime = 120;
359                         c.flood = atoi(flood);
360                         c.threshold = 5;
361                         c.sendqmax = 262144; // 256k
362                         c.recvqmax = 4096;   // 4k
363                         if (atoi(thold)>0)
364                         {
365                                 c.threshold = atoi(thold);
366                         }
367                         if (atoi(sqmax)>0)
368                         {
369                                 c.sendqmax = atoi(sqmax);
370                         }
371                         if (atoi(rqmax)>0)
372                         {
373                                 c.recvqmax = atoi(rqmax);
374                         }
375                         if (atoi(timeout)>0)
376                         {
377                                 c.registration_timeout = atoi(timeout);
378                         }
379                         if (atoi(pfreq)>0)
380                         {
381                                 c.pingtime = atoi(pfreq);
382                         }
383                         Classes.push_back(c);
384                         log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%lu flood=%lu",c.host,c.pass,(unsigned long)c.registration_timeout,(unsigned long)c.flood);
385                 }
386                 else
387                 {
388                         ConfValue("connect","deny",i,Value,&config_f);
389                         strlcpy(c.host,Value,MAXBUF);
390                         c.type = CC_DENY;
391                         Classes.push_back(c);
392                         log(DEBUG,"Read connect class type DENY, host=%s",c.host);
393                 }
394         
395         }
396         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
397         read_xline_defaults();
398         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
399         apply_lines(APPLY_ALL);
400
401         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
402         if (!bail)
403         {
404                 log(DEFAULT,"Adding and removing modules due to rehash...");
405
406                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
407
408                 // store the old module names
409                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
410                 {
411                         old_module_names.push_back(*t);
412                 }
413
414                 // get the new module names
415                 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
416                 {
417                         ConfValue("module","name",count2,Value,&config_f);
418                         new_module_names.push_back(Value);
419                 }
420
421                 // now create a list of new modules that are due to be loaded
422                 // and a seperate list of modules which are due to be unloaded
423                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
424                 {
425                         bool added = true;
426                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
427                         {
428                                 if (*old == *_new)
429                                         added = false;
430                         }
431                         if (added)
432                                 added_modules.push_back(*_new);
433                 }
434                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
435                 {
436                         bool removed = true;
437                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
438                         {
439                                 if (*newm == *oldm)
440                                         removed = false;
441                         }
442                         if (removed)
443                                 removed_modules.push_back(*oldm);
444                 }
445                 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
446                 // to be removed.
447                 int rem = 0, add = 0;
448                 if (!removed_modules.empty())
449                 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
450                 {
451                         if (UnloadModule(removing->c_str()))
452                         {
453                                 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
454                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
455                                 rem++;
456                         }
457                         else
458                         {
459                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
460                         }
461                 }
462                 if (!added_modules.empty())
463                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
464                 {
465                         if (LoadModule(adding->c_str()))
466                         {
467                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
468                                 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
469                                 add++;
470                         }
471                         else
472                         {
473                                 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
474                         }
475                 }
476                 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
477         }
478 }
479
480
481 /* add a channel to a user, creating the record for it if needed and linking
482  * it to the user record */
483
484 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
485 {
486         if ((!user) || (!cn))
487         {
488                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
489                 return 0;
490         }
491
492         int created = 0;
493         char cname[MAXBUF];
494         int MOD_RESULT = 0;
495         strncpy(cname,cn,CHANMAX);
496
497         log(DEBUG,"add_channel: %s %s",user->nick,cname);
498
499         chanrec* Ptr = FindChan(cname);
500
501         if (!Ptr)
502         {
503                 if (user->fd > -1)
504                 {
505                         MOD_RESULT = 0;
506                         FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
507                         if (MOD_RESULT == 1)
508                                 return NULL;
509                 }
510                 /* create a new one */
511                 chanlist[cname] = new chanrec();
512                 strlcpy(chanlist[cname]->name, cname,CHANMAX);
513                 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
514                 chanlist[cname]->created = TIME;
515                 strcpy(chanlist[cname]->topic, "");
516                 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
517                 chanlist[cname]->topicset = 0;
518                 Ptr = chanlist[cname];
519                 log(DEBUG,"add_channel: created: %s",cname);
520                 /* set created to 2 to indicate user
521                  * is the first in the channel
522                  * and should be given ops */
523                 created = 2;
524         }
525         else
526         {
527                 /* Already on the channel */
528                 if (has_channel(user,Ptr))
529                         return NULL;
530                         
531                 // remote users are allowed us to bypass channel modes
532                 // and bans (used by servers)
533                 if (user->fd > -1)
534                 {
535                         MOD_RESULT = 0;
536                         FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
537                         if (MOD_RESULT == 1)
538                         {
539                                 return NULL;
540                         }
541                         else
542                         {
543                                 if (*Ptr->key)
544                                 {
545                                         MOD_RESULT = 0;
546                                         FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
547                                         if (!MOD_RESULT)
548                                         {
549                                                 if (!key)
550                                                 {
551                                                         log(DEBUG,"add_channel: no key given in JOIN");
552                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
553                                                         return NULL;
554                                                 }
555                                                 else
556                                                 {
557                                                         if (strcasecmp(key,Ptr->key))
558                                                         {
559                                                                 log(DEBUG,"add_channel: bad key given in JOIN");
560                                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
561                                                                 return NULL;
562                                                         }
563                                                 }
564                                         }
565                                 }
566                                 if (Ptr->binarymodes & CM_INVITEONLY)
567                                 {
568                                         MOD_RESULT = 0;
569                                         FOREACH_RESULT(OnCheckInvite(user, Ptr));
570                                         if (!MOD_RESULT)
571                                         {
572                                                 log(DEBUG,"add_channel: channel is +i");
573                                                 if (user->IsInvited(Ptr->name))
574                                                 {
575                                                         /* user was invited to channel */
576                                                         /* there may be an optional channel NOTICE here */
577                                                 }
578                                                 else
579                                                 {
580                                                         WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
581                                                         return NULL;
582                                                 }
583                                         }
584                                         user->RemoveInvite(Ptr->name);
585                                 }
586                                 if (Ptr->limit)
587                                 {
588                                         MOD_RESULT = 0;
589                                         FOREACH_RESULT(OnCheckLimit(user, Ptr));
590                                         if (!MOD_RESULT)
591                                         {
592                                                 if (usercount(Ptr) >= Ptr->limit)
593                                                 {
594                                                         WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
595                                                         return NULL;
596                                                 }
597                                         }
598                                 }
599                                 if (Ptr->bans.size())
600                                 {
601                                         log(DEBUG,"add_channel: about to walk banlist");
602                                         MOD_RESULT = 0;
603                                         FOREACH_RESULT(OnCheckBan(user, Ptr));
604                                         if (!MOD_RESULT)
605                                         {
606                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
607                                                 {
608                                                         if (match(user->GetFullHost(),i->data))
609                                                         {
610                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
611                                                                 return NULL;
612                                                         }
613                                                 }
614                                         }
615                                 }
616                         }
617                 }
618                 else
619                 {
620                         log(DEBUG,"Overridden checks");
621                 }
622                 created = 1;
623         }
624
625         log(DEBUG,"Passed channel checks");
626         
627         for (unsigned int index =0; index < user->chans.size(); index++)
628         {
629                 if (user->chans[index].channel == NULL)
630                 {
631                         return ForceChan(Ptr,user->chans[index],user,created);
632                 }
633         }
634         /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
635          * and put the channel in here. Same for remote users which are not bound by
636          * the channel limits. Otherwise, nope, youre boned.
637          */
638         if (user->fd < 0)
639         {
640                 ucrec a;
641                 chanrec* c = ForceChan(Ptr,a,user,created);
642                 user->chans.push_back(a);
643                 return c;
644         }
645         else if (strchr(user->modes,'o'))
646         {
647                 /* Oper allows extension up to the OPERMAXCHANS value */
648                 if (user->chans.size() < OPERMAXCHANS)
649                 {
650                         ucrec a;
651                         chanrec* c = ForceChan(Ptr,a,user,created);
652                         user->chans.push_back(a);
653                         return c;
654                 }
655         }
656         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
657         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
658         return NULL;
659 }
660
661 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
662 {
663         if (created == 2)
664         {
665                 /* first user in is given ops */
666                 a.uc_modes = UCMODE_OP;
667         }
668         else
669         {
670                 a.uc_modes = 0;
671         }
672         a.channel = Ptr;
673         Ptr->AddUser((char*)user);
674         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
675         log(DEBUG,"Sent JOIN to client");
676         if (Ptr->topicset)
677         {
678                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
679                 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
680         }
681         userlist(user,Ptr);
682         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
683         FOREACH_MOD OnUserJoin(user,Ptr);
684         return Ptr;
685 }
686
687 /* remove a channel from a users record, and remove the record from memory
688  * if the channel has become empty */
689
690 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
691 {
692         if ((!user) || (!cname))
693         {
694                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
695                 return NULL;
696         }
697
698         chanrec* Ptr = FindChan(cname);
699         
700         if (!Ptr)
701                 return NULL;
702
703         FOREACH_MOD OnUserPart(user,Ptr);
704         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
705         
706         for (unsigned int i =0; i < user->chans.size(); i++)
707         {
708                 /* zap it from the channel list of the user */
709                 if (user->chans[i].channel == Ptr)
710                 {
711                         if (reason)
712                         {
713                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
714                         }
715                         else
716                         {
717                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
718                         }
719                         user->chans[i].uc_modes = 0;
720                         user->chans[i].channel = NULL;
721                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
722                         break;
723                 }
724         }
725
726         Ptr->DelUser((char*)user);
727         
728         /* if there are no users left on the channel */
729         if (!usercount(Ptr))
730         {
731                 chan_hash::iterator iter = chanlist.find(Ptr->name);
732
733                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
734
735                 /* kill the record */
736                 if (iter != chanlist.end())
737                 {
738                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
739                         delete Ptr;
740                         chanlist.erase(iter);
741                 }
742         }
743
744         return NULL;
745 }
746
747
748 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
749 {
750         if ((!src) || (!user) || (!Ptr) || (!reason))
751         {
752                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
753                 return;
754         }
755
756         if ((!Ptr) || (!user) || (!src))
757         {
758                 return;
759         }
760
761         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
762
763         if (!has_channel(user,Ptr))
764         {
765                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
766                 return;
767         }
768
769         int MOD_RESULT = 0;
770         FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
771         if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
772                 return;
773
774         if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
775         {
776                 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
777                 {
778                         if (cstatus(src,Ptr) == STATUS_HOP)
779                         {
780                                 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
781                         }
782                         else
783                         {
784                                 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
785                         }
786                         
787                         return;
788                 }
789         }
790
791         if (!is_uline(src->server))
792         {
793                 MOD_RESULT = 0;
794                 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
795                 if (MOD_RESULT)
796                         return;
797         }
798
799         FOREACH_MOD OnUserKick(src,user,Ptr,reason);
800
801         for (unsigned int i =0; i < user->chans.size(); i++)
802         {
803                 /* zap it from the channel list of the user */
804                 if (user->chans[i].channel)
805                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
806                 {
807                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
808                         user->chans[i].uc_modes = 0;
809                         user->chans[i].channel = NULL;
810                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
811                         break;
812                 }
813         }
814
815         Ptr->DelUser((char*)user);
816
817         /* if there are no users left on the channel */
818         if (!usercount(Ptr))
819         {
820                 chan_hash::iterator iter = chanlist.find(Ptr->name);
821
822                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
823
824                 /* kill the record */
825                 if (iter != chanlist.end())
826                 {
827                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
828                         delete Ptr;
829                         chanlist.erase(iter);
830                 }
831         }
832 }
833
834
835
836
837 /* This function pokes and hacks at a parameter list like the following:
838  *
839  * PART #winbot,#darkgalaxy :m00!
840  *
841  * to turn it into a series of individual calls like this:
842  *
843  * PART #winbot :m00!
844  * PART #darkgalaxy :m00!
845  *
846  * The seperate calls are sent to a callback function provided by the caller
847  * (the caller will usually call itself recursively). The callback function
848  * must be a command handler. Calling this function on a line with no list causes
849  * no action to be taken. You must provide a starting and ending parameter number
850  * where the range of the list can be found, useful if you have a terminating
851  * parameter as above which is actually not part of the list, or parameters
852  * before the actual list as well. This code is used by many functions which
853  * can function as "one to list" (see the RFC) */
854
855 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
856 {
857         char plist[MAXBUF];
858         char *param;
859         char *pars[32];
860         char blog[32][MAXBUF];
861         char blog2[32][MAXBUF];
862         int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
863         char keystr[MAXBUF];
864         char moo[MAXBUF];
865
866         for (int i = 0; i <32; i++)
867                 strcpy(blog[i],"");
868
869         for (int i = 0; i <32; i++)
870                 strcpy(blog2[i],"");
871
872         strcpy(moo,"");
873         for (int i = 0; i <10; i++)
874         {
875                 if (!parameters[i])
876                 {
877                         parameters[i] = moo;
878                 }
879         }
880         if (joins)
881         {
882                 if (pcnt > 1) /* we have a key to copy */
883                 {
884                         strlcpy(keystr,parameters[1],MAXBUF);
885                 }
886         }
887
888         if (!parameters[start])
889         {
890                 return 0;
891         }
892         if (!strchr(parameters[start],','))
893         {
894                 return 0;
895         }
896         strcpy(plist,"");
897         for (int i = start; i <= end; i++)
898         {
899                 if (parameters[i])
900                 {
901                         strlcat(plist,parameters[i],MAXBUF);
902                 }
903         }
904         
905         j = 0;
906         param = plist;
907
908         t = strlen(plist);
909         for (int i = 0; i < t; i++)
910         {
911                 if (plist[i] == ',')
912                 {
913                         plist[i] = '\0';
914                         strlcpy(blog[j++],param,MAXBUF);
915                         param = plist+i+1;
916                         if (j>20)
917                         {
918                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
919                                 return 1;
920                         }
921                 }
922         }
923         strlcpy(blog[j++],param,MAXBUF);
924         total = j;
925
926         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
927         {
928                 strcat(keystr,",");
929         }
930         
931         if ((joins) && (keystr))
932         {
933                 if (strchr(keystr,','))
934                 {
935                         j = 0;
936                         param = keystr;
937                         t2 = strlen(keystr);
938                         for (int i = 0; i < t2; i++)
939                         {
940                                 if (keystr[i] == ',')
941                                 {
942                                         keystr[i] = '\0';
943                                         strlcpy(blog2[j++],param,MAXBUF);
944                                         param = keystr+i+1;
945                                 }
946                         }
947                         strlcpy(blog2[j++],param,MAXBUF);
948                         total2 = j;
949                 }
950         }
951
952         for (j = 0; j < total; j++)
953         {
954                 if (blog[j])
955                 {
956                         pars[0] = blog[j];
957                 }
958                 for (q = end; q < pcnt-1; q++)
959                 {
960                         if (parameters[q+1])
961                         {
962                                 pars[q-end+1] = parameters[q+1];
963                         }
964                 }
965                 if ((joins) && (parameters[1]))
966                 {
967                         if (pcnt > 1)
968                         {
969                                 pars[1] = blog2[j];
970                         }
971                         else
972                         {
973                                 pars[1] = NULL;
974                         }
975                 }
976                 /* repeatedly call the function with the hacked parameter list */
977                 if ((joins) && (pcnt > 1))
978                 {
979                         if (pars[1])
980                         {
981                                 // pars[1] already set up and containing key from blog2[j]
982                                 fn(pars,2,u);
983                         }
984                         else
985                         {
986                                 pars[1] = parameters[1];
987                                 fn(pars,2,u);
988                         }
989                 }
990                 else
991                 {
992                         fn(pars,pcnt-(end-start),u);
993                 }
994         }
995
996         return 1;
997 }
998
999
1000
1001 void kill_link(userrec *user,const char* r)
1002 {
1003         user_hash::iterator iter = clientlist.find(user->nick);
1004         
1005         char reason[MAXBUF];
1006         
1007         strncpy(reason,r,MAXBUF);
1008
1009         if (strlen(reason)>MAXQUIT)
1010         {
1011                 reason[MAXQUIT-1] = '\0';
1012         }
1013
1014         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1015         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1016         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1017
1018         if (user->registered == 7) {
1019                 FOREACH_MOD OnUserQuit(user,reason);
1020                 WriteCommonExcept(user,"QUIT :%s",reason);
1021         }
1022
1023         user->FlushWriteBuf();
1024
1025         FOREACH_MOD OnUserDisconnect(user);
1026
1027         if (user->fd > -1)
1028         {
1029                 FOREACH_MOD OnRawSocketClose(user->fd);
1030                 SE->DelFd(user->fd);
1031                 user->CloseSocket();
1032         }
1033
1034         // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1035         // if they were an oper with +s.
1036         if (user->registered == 7) {
1037                 purge_empty_chans(user);
1038                 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1039                 if (user->fd > -1)
1040                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1041                 AddWhoWas(user);
1042         }
1043
1044         if (iter != clientlist.end())
1045         {
1046                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1047                 if (user->fd > -1)
1048                         fd_ref_table[user->fd] = NULL;
1049                 clientlist.erase(iter);
1050         }
1051         delete user;
1052 }
1053
1054 void kill_link_silent(userrec *user,const char* r)
1055 {
1056         user_hash::iterator iter = clientlist.find(user->nick);
1057         
1058         char reason[MAXBUF];
1059         
1060         strncpy(reason,r,MAXBUF);
1061
1062         if (strlen(reason)>MAXQUIT)
1063         {
1064                 reason[MAXQUIT-1] = '\0';
1065         }
1066
1067         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1068         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1069         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1070
1071         user->FlushWriteBuf();
1072
1073         if (user->registered == 7) {
1074                 FOREACH_MOD OnUserQuit(user,reason);
1075                 WriteCommonExcept(user,"QUIT :%s",reason);
1076         }
1077
1078         FOREACH_MOD OnUserDisconnect(user);
1079
1080         if (user->fd > -1)
1081         {
1082                 FOREACH_MOD OnRawSocketClose(user->fd);
1083                 SE->DelFd(user->fd);
1084                 user->CloseSocket();
1085         }
1086
1087         if (user->registered == 7) {
1088                 purge_empty_chans(user);
1089         }
1090         
1091         if (iter != clientlist.end())
1092         {
1093                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1094                 if (user->fd > -1)
1095                         fd_ref_table[user->fd] = NULL;
1096                 clientlist.erase(iter);
1097         }
1098         delete user;
1099 }
1100
1101
1102 int main(int argc, char** argv)
1103 {
1104         Start();
1105         srand(time(NULL));
1106         log(DEBUG,"*** InspIRCd starting up!");
1107         if (!FileExists(CONFIG_FILE))
1108         {
1109                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1110                 log(DEFAULT,"main: no config");
1111                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1112                 Exit(ERROR);
1113         }
1114         if (argc > 1) {
1115                 for (int i = 1; i < argc; i++)
1116                 {
1117                         if (!strcmp(argv[i],"-nofork")) {
1118                                 nofork = true;
1119                         }
1120                         if (!strcmp(argv[i],"-wait")) {
1121                                 sleep(6);
1122                         }
1123                         if (!strcmp(argv[i],"-nolimit")) {
1124                                 unlimitcore = true;
1125                         }
1126                 }
1127         }
1128
1129         strlcpy(MyExecutable,argv[0],MAXBUF);
1130         
1131         // initialize the lowercase mapping table
1132         for (unsigned int cn = 0; cn < 256; cn++)
1133                 lowermap[cn] = cn;
1134         // lowercase the uppercase chars
1135         for (unsigned int cn = 65; cn < 91; cn++)
1136                 lowermap[cn] = tolower(cn);
1137         // now replace the specific chars for scandanavian comparison
1138         lowermap[(unsigned)'['] = '{';
1139         lowermap[(unsigned)']'] = '}';
1140         lowermap[(unsigned)'\\'] = '|';
1141
1142         if (InspIRCd(argv,argc) == ERROR)
1143         {
1144                 log(DEFAULT,"main: daemon function bailed");
1145                 printf("ERROR: could not initialise. Shutting down.\n");
1146                 Exit(ERROR);
1147         }
1148         Exit(TRUE);
1149         return 0;
1150 }
1151
1152 template<typename T> inline string ConvToStr(const T &in)
1153 {
1154         stringstream tmp;
1155         if (!(tmp << in)) return string();
1156         return tmp.str();
1157 }
1158
1159 /* re-allocates a nick in the user_hash after they change nicknames,
1160  * returns a pointer to the new user as it may have moved */
1161
1162 userrec* ReHashNick(char* Old, char* New)
1163 {
1164         //user_hash::iterator newnick;
1165         user_hash::iterator oldnick = clientlist.find(Old);
1166
1167         log(DEBUG,"ReHashNick: %s %s",Old,New);
1168         
1169         if (!strcasecmp(Old,New))
1170         {
1171                 log(DEBUG,"old nick is new nick, skipping");
1172                 return oldnick->second;
1173         }
1174         
1175         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1176
1177         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1178
1179         userrec* olduser = oldnick->second;
1180         clientlist[New] = olduser;
1181         clientlist.erase(oldnick);
1182
1183         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1184         
1185         return clientlist[New];
1186 }
1187
1188 /* adds or updates an entry in the whowas list */
1189 void AddWhoWas(userrec* u)
1190 {
1191         whowas_hash::iterator iter = whowas.find(u->nick);
1192         WhoWasUser *a = new WhoWasUser();
1193         strlcpy(a->nick,u->nick,NICKMAX);
1194         strlcpy(a->ident,u->ident,IDENTMAX);
1195         strlcpy(a->dhost,u->dhost,160);
1196         strlcpy(a->host,u->host,160);
1197         strlcpy(a->fullname,u->fullname,MAXGECOS);
1198         strlcpy(a->server,u->server,256);
1199         a->signon = u->signon;
1200
1201         /* MAX_WHOWAS:   max number of /WHOWAS items
1202          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1203          *               can be replaced by a newer one
1204          */
1205         
1206         if (iter == whowas.end())
1207         {
1208                 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1209                 {
1210                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1211                         {
1212                                 // 3600 seconds in an hour ;)
1213                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1214                                 {
1215                                         // delete the old one
1216                                         if (i->second) delete i->second;
1217                                         // replace with new one
1218                                         i->second = a;
1219                                         log(DEBUG,"added WHOWAS entry, purged an old record");
1220                                         return;
1221                                 }
1222                         }
1223                         // no space left and user doesnt exist. Don't leave ram in use!
1224                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1225                         delete a;
1226                 }
1227                 else
1228                 {
1229                         log(DEBUG,"added fresh WHOWAS entry");
1230                         whowas[a->nick] = a;
1231                 }
1232         }
1233         else
1234         {
1235                 log(DEBUG,"updated WHOWAS entry");
1236                 if (iter->second) delete iter->second;
1237                 iter->second = a;
1238         }
1239 }
1240
1241 #ifdef THREADED_DNS
1242 void* dns_task(void* arg)
1243 {
1244         userrec* u = (userrec*)arg;
1245         log(DEBUG,"DNS thread for user %s",u->nick);
1246         DNS dns1;
1247         DNS dns2;
1248         std::string host;
1249         std::string ip;
1250         if (dns1.ReverseLookup(u->ip))
1251         {
1252                 log(DEBUG,"DNS Step 1");
1253                 while (!dns1.HasResult())
1254                 {
1255                         usleep(100);
1256                 }
1257                 host = dns1.GetResult();
1258                 if (host != "")
1259                 {
1260                         log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1261                         if (dns2.ForwardLookup(host))
1262                         {
1263                                 while (!dns2.HasResult())
1264                                 {
1265                                         usleep(100);
1266                                 }
1267                                 ip = dns2.GetResultIP();
1268                                 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1269                                 if (ip == std::string(u->ip))
1270                                 {
1271                                         log(DEBUG,"DNS Step 4");
1272                                         if (host.length() < 160)
1273                                         {
1274                                                 log(DEBUG,"DNS Step 5");
1275                                                 strcpy(u->host,host.c_str());
1276                                                 strcpy(u->dhost,host.c_str());
1277                                         }
1278                                 }
1279                         }
1280                 }
1281         }
1282         u->dns_done = true;
1283         return NULL;
1284 }
1285 #endif
1286
1287 /* add a client connection to the sockets list */
1288 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1289 {
1290         string tempnick;
1291         char tn2[MAXBUF];
1292         user_hash::iterator iter;
1293
1294         tempnick = ConvToStr(socket) + "-unknown";
1295         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1296
1297         iter = clientlist.find(tempnick);
1298
1299         // fix by brain.
1300         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1301         // using one as a registered connection. As theyre per fd, we can also safely assume
1302         // that we wont have collisions. Therefore, if the nick exists in the list, its only
1303         // used by a dead socket, erase the iterator so that the new client may reclaim it.
1304         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1305         // issue in earlier alphas/betas
1306         if (iter != clientlist.end())
1307         {
1308                 userrec* goner = iter->second;
1309                 delete goner;
1310                 clientlist.erase(iter);
1311         }
1312
1313         /*
1314          * It is OK to access the value here this way since we know
1315          * it exists, we just created it above.
1316          *
1317          * At NO other time should you access a value in a map or a
1318          * hash_map this way.
1319          */
1320         clientlist[tempnick] = new userrec();
1321
1322         NonBlocking(socket);
1323         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1324
1325         clientlist[tempnick]->fd = socket;
1326         strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1327         strlcpy(clientlist[tempnick]->host, host,160);
1328         strlcpy(clientlist[tempnick]->dhost, host,160);
1329         clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
1330         strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1331         clientlist[tempnick]->registered = 0;
1332         clientlist[tempnick]->signon = TIME+dns_timeout;
1333         clientlist[tempnick]->lastping = 1;
1334         clientlist[tempnick]->port = port;
1335         strlcpy(clientlist[tempnick]->ip,ip,16);
1336
1337         // set the registration timeout for this user
1338         unsigned long class_regtimeout = 90;
1339         int class_flood = 0;
1340         long class_threshold = 5;
1341         long class_sqmax = 262144;      // 256kb
1342         long class_rqmax = 4096;        // 4k
1343
1344         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1345         {
1346                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1347                 {
1348                         class_regtimeout = (unsigned long)i->registration_timeout;
1349                         class_flood = i->flood;
1350                         clientlist[tempnick]->pingmax = i->pingtime;
1351                         class_threshold = i->threshold;
1352                         class_sqmax = i->sendqmax;
1353                         class_rqmax = i->recvqmax;
1354                         break;
1355                 }
1356         }
1357
1358         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1359         clientlist[tempnick]->timeout = TIME+class_regtimeout;
1360         clientlist[tempnick]->flood = class_flood;
1361         clientlist[tempnick]->threshold = class_threshold;
1362         clientlist[tempnick]->sendqmax = class_sqmax;
1363         clientlist[tempnick]->recvqmax = class_rqmax;
1364
1365         ucrec a;
1366         a.channel = NULL;
1367         a.uc_modes = 0;
1368         for (int i = 0; i < MAXCHANS; i++)
1369                 clientlist[tempnick]->chans.push_back(a);
1370
1371         if (clientlist.size() > SoftLimit)
1372         {
1373                 kill_link(clientlist[tempnick],"No more connections allowed");
1374                 return;
1375         }
1376
1377         if (clientlist.size() >= MAXCLIENTS)
1378         {
1379                 kill_link(clientlist[tempnick],"No more connections allowed");
1380                 return;
1381         }
1382
1383         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1384         // its a pretty big but for the moment valid assumption:
1385         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1386         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1387         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1388         // which for the time being is a physical impossibility (even the largest networks dont have more
1389         // than about 10,000 users on ONE server!)
1390         if ((unsigned)socket > 65534)
1391         {
1392                 kill_link(clientlist[tempnick],"Server is full");
1393                 return;
1394         }
1395                 
1396
1397         char* e = matches_exception(ip);
1398         if (!e)
1399         {
1400                 char* r = matches_zline(ip);
1401                 if (r)
1402                 {
1403                         char reason[MAXBUF];
1404                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1405                         kill_link(clientlist[tempnick],reason);
1406                         return;
1407                 }
1408         }
1409         fd_ref_table[socket] = clientlist[tempnick];
1410         SE->AddFd(socket,true,X_ESTAB_CLIENT);
1411 }
1412
1413 /* shows the message of the day, and any other on-logon stuff */
1414 void FullConnectUser(userrec* user)
1415 {
1416         stats->statsConnects++;
1417         user->idle_lastmsg = TIME;
1418         log(DEBUG,"ConnectUser: %s",user->nick);
1419
1420         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1421         {
1422                 kill_link(user,"Invalid password");
1423                 return;
1424         }
1425         if (IsDenied(user))
1426         {
1427                 kill_link(user,"Unauthorised connection");
1428                 return;
1429         }
1430
1431         char match_against[MAXBUF];
1432         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1433         char* e = matches_exception(match_against);
1434         if (!e)
1435         {
1436                 char* r = matches_gline(match_against);
1437                 if (r)
1438                 {
1439                         char reason[MAXBUF];
1440                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1441                         kill_link_silent(user,reason);
1442                         return;
1443                 }
1444                 r = matches_kline(user->host);
1445                 if (r)
1446                 {
1447                         char reason[MAXBUF];
1448                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1449                         kill_link_silent(user,reason);
1450                         return;
1451                 }
1452         }
1453
1454
1455         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1456         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1457         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1458         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1459         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
1460         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1461         std::stringstream v;
1462         v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1463         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1464         v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1465         v << Network;
1466         std::string data005 = v.str();
1467         FOREACH_MOD On005Numeric(data005);
1468         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1469         // so i'd better split it :)
1470         std::stringstream out(data005);
1471         std::string token = "";
1472         std::string line5 = "";
1473         int token_counter = 0;
1474         while (!out.eof())
1475         {
1476                 out >> token;
1477                 line5 = line5 + token + " ";
1478                 token_counter++;
1479                 if ((token_counter >= 13) || (out.eof() == true))
1480                 {
1481                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1482                         line5 = "";
1483                         token_counter = 0;
1484                 }
1485         }
1486         ShowMOTD(user);
1487
1488         // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1489         // onto the network and produce 'fake direction'
1490         FOREACH_MOD OnUserConnect(user);
1491         FOREACH_MOD OnGlobalConnect(user);
1492         user->registered = 7;
1493         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1494 }
1495
1496
1497 /* shows the message of the day, and any other on-logon stuff */
1498 void ConnectUser(userrec *user)
1499 {
1500         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1501         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1502         {
1503                 FullConnectUser(user);
1504         }
1505 }
1506
1507 std::string GetVersionString()
1508 {
1509         char versiondata[MAXBUF];
1510 #ifdef THREADED_DNS
1511         char dnsengine[] = "multithread";
1512 #else
1513         char dnsengine[] = "singlethread";
1514 #endif
1515         snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision.c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1516         return versiondata;
1517 }
1518
1519 void handle_version(char **parameters, int pcnt, userrec *user)
1520 {
1521         WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1522 }
1523
1524
1525 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1526 {
1527         for (unsigned int i = 0; i < cmdlist.size(); i++)
1528         {
1529                 if (!strcasecmp(cmdlist[i].command,commandname))
1530                 {
1531                         if (cmdlist[i].handler_function)
1532                         {
1533                                 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1534                                 {
1535                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1536                                         {
1537                                                 if (cmdlist[i].flags_needed)
1538                                                 {
1539                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1540                                                         {
1541                                                                 return true;
1542                                                         }
1543                                                         else
1544                                                         {
1545                                                                 return false;
1546                                                         }
1547                                                 }
1548                                                 return true;
1549                                         }
1550                                 }
1551                         }
1552                 }
1553         }
1554         return false;
1555 }
1556
1557 // calls a handler function for a command
1558
1559 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1560 {
1561         for (unsigned int i = 0; i < cmdlist.size(); i++)
1562         {
1563                 if (!strcasecmp(cmdlist[i].command,commandname))
1564                 {
1565                         if (cmdlist[i].handler_function)
1566                         {
1567                                 if (pcnt>=cmdlist[i].min_params)
1568                                 {
1569                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1570                                         {
1571                                                 if (cmdlist[i].flags_needed)
1572                                                 {
1573                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1574                                                         {
1575                                                                 cmdlist[i].handler_function(parameters,pcnt,user);
1576                                                         }
1577                                                 }
1578                                                 else
1579                                                 {
1580                                                         cmdlist[i].handler_function(parameters,pcnt,user);
1581                                                 }
1582                                         }
1583                                 }
1584                         }
1585                 }
1586         }
1587 }
1588
1589
1590 void force_nickchange(userrec* user,const char* newnick)
1591 {
1592         char nick[MAXBUF];
1593         int MOD_RESULT = 0;
1594         
1595         strcpy(nick,"");
1596
1597         FOREACH_RESULT(OnUserPreNick(user,newnick));
1598         if (MOD_RESULT) {
1599                 stats->statsCollisions++;
1600                 kill_link(user,"Nickname collision");
1601                 return;
1602         }
1603         if (matches_qline(newnick))
1604         {
1605                 stats->statsCollisions++;
1606                 kill_link(user,"Nickname collision");
1607                 return;
1608         }
1609         
1610         if (user)
1611         {
1612                 if (newnick)
1613                 {
1614                         strncpy(nick,newnick,MAXBUF);
1615                 }
1616                 if (user->registered == 7)
1617                 {
1618                         char* pars[1];
1619                         pars[0] = nick;
1620                         handle_nick(pars,1,user);
1621                 }
1622         }
1623 }
1624                                 
1625
1626 int process_parameters(char **command_p,char *parameters)
1627 {
1628         int j = 0;
1629         int q = strlen(parameters);
1630         if (!q)
1631         {
1632                 /* no parameters, command_p invalid! */
1633                 return 0;
1634         }
1635         if (parameters[0] == ':')
1636         {
1637                 command_p[0] = parameters+1;
1638                 return 1;
1639         }
1640         if (q)
1641         {
1642                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1643                 {
1644                         /* only one parameter */
1645                         command_p[0] = parameters;
1646                         if (parameters[0] == ':')
1647                         {
1648                                 if (strchr(parameters,' ') != NULL)
1649                                 {
1650                                         command_p[0]++;
1651                                 }
1652                         }
1653                         return 1;
1654                 }
1655         }
1656         command_p[j++] = parameters;
1657         for (int i = 0; i <= q; i++)
1658         {
1659                 if (parameters[i] == ' ')
1660                 {
1661                         command_p[j++] = parameters+i+1;
1662                         parameters[i] = '\0';
1663                         if (command_p[j-1][0] == ':')
1664                         {
1665                                 *command_p[j-1]++; /* remove dodgy ":" */
1666                                 break;
1667                                 /* parameter like this marks end of the sequence */
1668                         }
1669                 }
1670         }
1671         return j; /* returns total number of items in the list */
1672 }
1673
1674 void process_command(userrec *user, char* cmd)
1675 {
1676         char *parameters;
1677         char *command;
1678         char *command_p[127];
1679         char p[MAXBUF], temp[MAXBUF];
1680         int j, items, cmd_found;
1681
1682         for (int i = 0; i < 127; i++)
1683                 command_p[i] = NULL;
1684
1685         if (!user)
1686         {
1687                 return;
1688         }
1689         if (!cmd)
1690         {
1691                 return;
1692         }
1693         if (!cmd[0])
1694         {
1695                 return;
1696         }
1697         
1698         int total_params = 0;
1699         if (strlen(cmd)>2)
1700         {
1701                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1702                 {
1703                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1704                         {
1705                                 total_params++;
1706                                 // found a 'trailing', we dont count them after this.
1707                                 break;
1708                         }
1709                         if (cmd[q] == ' ')
1710                                 total_params++;
1711                 }
1712         }
1713
1714         // another phidjit bug...
1715         if (total_params > 126)
1716         {
1717                 *(strchr(cmd,' ')) = '\0';
1718                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1719                 return;
1720         }
1721
1722         strlcpy(temp,cmd,MAXBUF);
1723         
1724         std::string tmp = cmd;
1725         for (int i = 0; i <= MODCOUNT; i++)
1726         {
1727                 std::string oldtmp = tmp;
1728                 modules[i]->OnServerRaw(tmp,true,user);
1729                 if (oldtmp != tmp)
1730                 {
1731                         log(DEBUG,"A Module changed the input string!");
1732                         log(DEBUG,"New string: %s",tmp.c_str());
1733                         log(DEBUG,"Old string: %s",oldtmp.c_str());
1734                         break;
1735                 }
1736         }
1737         strlcpy(cmd,tmp.c_str(),MAXBUF);
1738         strlcpy(temp,cmd,MAXBUF);
1739
1740         if (!strchr(cmd,' '))
1741         {
1742                 /* no parameters, lets skip the formalities and not chop up
1743                  * the string */
1744                 log(DEBUG,"About to preprocess command with no params");
1745                 items = 0;
1746                 command_p[0] = NULL;
1747                 parameters = NULL;
1748                 for (unsigned int i = 0; i <= strlen(cmd); i++)
1749                 {
1750                         cmd[i] = toupper(cmd[i]);
1751                 }
1752                 command = cmd;
1753         }
1754         else
1755         {
1756                 strcpy(cmd,"");
1757                 j = 0;
1758                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1759                 for (unsigned int i = 0; i < strlen(temp); i++)
1760                 {
1761                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1762                         {
1763                                 cmd[j++] = temp[i];
1764                                 cmd[j] = 0;
1765                         }
1766                 }
1767                 /* split the full string into a command plus parameters */
1768                 parameters = p;
1769                 strcpy(p," ");
1770                 command = cmd;
1771                 if (strchr(cmd,' '))
1772                 {
1773                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1774                         {
1775                                 /* capitalise the command ONLY, leave params intact */
1776                                 cmd[i] = toupper(cmd[i]);
1777                                 /* are we nearly there yet?! :P */
1778                                 if (cmd[i] == ' ')
1779                                 {
1780                                         command = cmd;
1781                                         parameters = cmd+i+1;
1782                                         cmd[i] = '\0';
1783                                         break;
1784                                 }
1785                         }
1786                 }
1787                 else
1788                 {
1789                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1790                         {
1791                                 cmd[i] = toupper(cmd[i]);
1792                         }
1793                 }
1794
1795         }
1796         cmd_found = 0;
1797         
1798         if (strlen(command)>MAXCOMMAND)
1799         {
1800                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1801                 return;
1802         }
1803         
1804         for (unsigned int x = 0; x < strlen(command); x++)
1805         {
1806                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1807                 {
1808                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1809                         {
1810                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1811                                 {
1812                                         stats->statsUnknown++;
1813                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1814                                         return;
1815                                 }
1816                         }
1817                 }
1818         }
1819
1820         for (unsigned int i = 0; i != cmdlist.size(); i++)
1821         {
1822                 if (cmdlist[i].command[0])
1823                 {
1824                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1825                         {
1826                                 if (parameters)
1827                                 {
1828                                         if (parameters[0])
1829                                         {
1830                                                 items = process_parameters(command_p,parameters);
1831                                         }
1832                                         else
1833                                         {
1834                                                 items = 0;
1835                                                 command_p[0] = NULL;
1836                                         }
1837                                 }
1838                                 else
1839                                 {
1840                                         items = 0;
1841                                         command_p[0] = NULL;
1842                                 }
1843                                 
1844                                 if (user)
1845                                 {
1846                                         /* activity resets the ping pending timer */
1847                                         user->nping = TIME + user->pingmax;
1848                                         if ((items) < cmdlist[i].min_params)
1849                                         {
1850                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1851                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1852                                                 return;
1853                                         }
1854                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1855                                         {
1856                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1857                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1858                                                 cmd_found = 1;
1859                                                 return;
1860                                         }
1861                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1862                                         {
1863                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1864                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1865                                                 cmd_found = 1;
1866                                                 return;
1867                                         }
1868                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
1869                                          * deny command! */
1870                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1871                                         {
1872                                                 if ((!isnick(user->nick)) || (user->registered != 7))
1873                                                 {
1874                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1875                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
1876                                                         return;
1877                                                 }
1878                                         }
1879                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
1880                                         {
1881                                                 std::stringstream dcmds(DisabledCommands);
1882                                                 while (!dcmds.eof())
1883                                                 {
1884                                                         std::string thiscmd;
1885                                                         dcmds >> thiscmd;
1886                                                         if (!strcasecmp(thiscmd.c_str(),command))
1887                                                         {
1888                                                                 // command is disabled!
1889                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1890                                                                 return;
1891                                                         }
1892                                                 }
1893                                         }
1894                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1895                                         {
1896                                                 if (cmdlist[i].handler_function)
1897                                                 {
1898                                                         
1899                                                         /* ikky /stats counters */
1900                                                         if (temp)
1901                                                         {
1902                                                                 cmdlist[i].use_count++;
1903                                                                 cmdlist[i].total_bytes+=strlen(temp);
1904                                                         }
1905
1906                                                         int MOD_RESULT = 0;
1907                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1908                                                         if (MOD_RESULT == 1) {
1909                                                                 return;
1910                                                         }
1911
1912                                                         /* WARNING: nothing may come after the
1913                                                          * command handler call, as the handler
1914                                                          * may free the user structure! */
1915
1916                                                         cmdlist[i].handler_function(command_p,items,user);
1917                                                 }
1918                                                 return;
1919                                         }
1920                                         else
1921                                         {
1922                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
1923                                                 return;
1924                                         }
1925                                 }
1926                                 cmd_found = 1;
1927                         }
1928                 }
1929         }
1930         if ((!cmd_found) && (user))
1931         {
1932                 stats->statsUnknown++;
1933                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1934         }
1935 }
1936
1937 bool removecommands(const char* source)
1938 {
1939         bool go_again = true;
1940         while (go_again)
1941         {
1942                 go_again = false;
1943                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1944                 {
1945                         if (!strcmp(i->source,source))
1946                         {
1947                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1948                                 cmdlist.erase(i);
1949                                 go_again = true;
1950                                 break;
1951                         }
1952                 }
1953         }
1954         return true;
1955 }
1956
1957
1958 void process_buffer(const char* cmdbuf,userrec *user)
1959 {
1960         if (!user)
1961         {
1962                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1963                 return;
1964         }
1965         char cmd[MAXBUF];
1966         if (!cmdbuf)
1967         {
1968                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1969                 return;
1970         }
1971         if (!cmdbuf[0])
1972         {
1973                 return;
1974         }
1975         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1976
1977         strlcpy(cmd,cmdbuf,MAXBUF);
1978         if (!cmd[0])
1979         {
1980                 return;
1981         }
1982         int sl = strlen(cmd)-1;
1983         if ((cmd[sl] == 13) || (cmd[sl] == 10))
1984         {
1985                 cmd[sl] = '\0';
1986         }
1987         sl = strlen(cmd)-1;
1988         if ((cmd[sl] == 13) || (cmd[sl] == 10))
1989         {
1990                 cmd[sl] = '\0';
1991         }
1992         sl = strlen(cmd)-1;
1993         while (cmd[sl] == ' ') // strip trailing spaces
1994         {
1995                 cmd[sl] = '\0';
1996                 sl = strlen(cmd)-1;
1997         }
1998
1999         if (!cmd[0])
2000         {
2001                 return;
2002         }
2003         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2004         tidystring(cmd);
2005         if ((user) && (cmd))
2006         {
2007                 process_command(user,cmd);
2008         }
2009 }
2010
2011 char MODERR[MAXBUF];
2012
2013 char* ModuleError()
2014 {
2015         return MODERR;
2016 }
2017
2018 void erase_factory(int j)
2019 {
2020         int v = 0;
2021         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2022         {
2023                 if (v == j)
2024                 {
2025                         factory.erase(t);
2026                         factory.push_back(NULL);
2027                         return;
2028                 }
2029                 v++;
2030         }
2031 }
2032
2033 void erase_module(int j)
2034 {
2035         int v1 = 0;
2036         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2037         {
2038                 if (v1 == j)
2039                 {
2040                         delete *m;
2041                         modules.erase(m);
2042                         modules.push_back(NULL);
2043                         break;
2044                 }
2045                 v1++;
2046         }
2047         int v2 = 0;
2048         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2049         {
2050                 if (v2 == j)
2051                 {
2052                        module_names.erase(v);
2053                        break;
2054                 }
2055                 v2++;
2056         }
2057
2058 }
2059
2060 bool UnloadModule(const char* filename)
2061 {
2062         std::string filename_str = filename;
2063         for (unsigned int j = 0; j != module_names.size(); j++)
2064         {
2065                 if (module_names[j] == filename_str)
2066                 {
2067                         if (modules[j]->GetVersion().Flags & VF_STATIC)
2068                         {
2069                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2070                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2071                                 return false;
2072                         }
2073                         /* Give the module a chance to tidy out all its metadata */
2074                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2075                         {
2076                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2077                         }
2078                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2079                         {
2080                                 modules[j]->OnCleanup(TYPE_USER,u->second);
2081                         }
2082                         FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2083                         // found the module
2084                         log(DEBUG,"Deleting module...");
2085                         erase_module(j);
2086                         log(DEBUG,"Erasing module entry...");
2087                         erase_factory(j);
2088                         log(DEBUG,"Removing dependent commands...");
2089                         removecommands(filename);
2090                         log(DEFAULT,"Module %s unloaded",filename);
2091                         MODCOUNT--;
2092                         return true;
2093                 }
2094         }
2095         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2096         snprintf(MODERR,MAXBUF,"Module not loaded");
2097         return false;
2098 }
2099
2100 bool LoadModule(const char* filename)
2101 {
2102         char modfile[MAXBUF];
2103 #ifdef STATIC_LINK
2104         snprintf(modfile,MAXBUF,"%s",filename);
2105 #else
2106         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2107 #endif
2108         std::string filename_str = filename;
2109 #ifndef STATIC_LINK
2110         if (!DirValid(modfile))
2111         {
2112                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2113                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2114                 return false;
2115         }
2116 #endif
2117         log(DEBUG,"Loading module: %s",modfile);
2118 #ifndef STATIC_LINK
2119         if (FileExists(modfile))
2120         {
2121 #endif
2122                 for (unsigned int j = 0; j < module_names.size(); j++)
2123                 {
2124                         if (module_names[j] == filename_str)
2125                         {
2126                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2127                                 snprintf(MODERR,MAXBUF,"Module already loaded");
2128                                 return false;
2129                         }
2130                 }
2131                 ircd_module* a = new ircd_module(modfile);
2132                 factory[MODCOUNT+1] = a;
2133                 if (factory[MODCOUNT+1]->LastError())
2134                 {
2135                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2136                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2137                         MODCOUNT--;
2138                         return false;
2139                 }
2140                 if (factory[MODCOUNT+1]->factory)
2141                 {
2142                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2143                         modules[MODCOUNT+1] = m;
2144                         /* save the module and the module's classfactory, if
2145                          * this isnt done, random crashes can occur :/ */
2146                         module_names.push_back(filename);
2147                 }
2148                 else
2149                 {
2150                         log(DEFAULT,"Unable to load %s",modfile);
2151                         snprintf(MODERR,MAXBUF,"Factory function failed!");
2152                         return false;
2153                 }
2154 #ifndef STATIC_LINK
2155         }
2156         else
2157         {
2158                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2159                 snprintf(MODERR,MAXBUF,"Module file could not be found");
2160                 return false;
2161         }
2162 #endif
2163         MODCOUNT++;
2164         FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2165         return true;
2166 }
2167
2168 int BindPorts()
2169 {
2170         char configToken[MAXBUF];
2171         int clientportcount = 0;
2172         for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2173         {
2174                 ConfValue("bind","port",count,configToken,&config_f);
2175                 ConfValue("bind","address",count,Addr,&config_f);
2176                 ConfValue("bind","type",count,Type,&config_f);
2177                 if (strcmp(Type,"servers"))
2178                 {
2179                         // modules handle server bind types now,
2180                         // its not a typo in the strcmp.
2181                         ports[clientportcount] = atoi(configToken);
2182                         strlcpy(addrs[clientportcount],Addr,256);
2183                         clientportcount++;
2184                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2185                 }
2186         }
2187         portCount = clientportcount;
2188
2189         for (int count = 0; count < portCount; count++)
2190         {
2191                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2192                 {
2193                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2194                         return(ERROR);
2195                 }
2196                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2197                 {
2198                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2199                 }
2200                 else    /* well we at least bound to one socket so we'll continue */
2201                 {
2202                         boundPortCount++;
2203                 }
2204         }
2205
2206         /* if we didn't bind to anything then abort */
2207         if (!boundPortCount)
2208         {
2209                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2210                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2211                 return (ERROR);
2212         }
2213
2214         return boundPortCount;
2215 }
2216
2217 int InspIRCd(char** argv, int argc)
2218 {
2219         bool expire_run = false;
2220         std::vector<int> activefds;
2221         int incomingSockfd;
2222         int in_port;
2223         userrec* cu = NULL;
2224         InspSocket* s = NULL;
2225         InspSocket* s_del = NULL;
2226         char* target;
2227         unsigned int numberactive;
2228         sockaddr_in sock_us;     // our port number
2229         socklen_t uslen;         // length of our port number
2230
2231         /* Beta 7 moved all this stuff out of the main function
2232          * into smaller sub-functions, much tidier -- Brain
2233          */
2234         OpenLog(argv, argc);
2235         CheckRoot();
2236         SetupCommandTable();
2237         ReadConfig(true,NULL);
2238         AddServerName(Config->ServerName);
2239         CheckDie();
2240         boundPortCount = BindPorts();
2241
2242         printf("\n");
2243         startup_time = time(NULL);
2244           
2245         char PID[MAXBUF];
2246         ConfValue("pid","file",0,PID,&config_f);
2247         // write once here, to try it out and make sure its ok
2248         WritePID(PID);
2249         
2250         if (!nofork)
2251         {
2252                 if (DaemonSeed() == ERROR)
2253                 {
2254                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
2255                         Exit(ERROR);
2256                 }
2257         }
2258
2259         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2260          * initialize the socket engine.
2261          */
2262         SE = new SocketEngine();
2263
2264         /* We must load the modules AFTER initializing the socket engine, now */
2265         LoadAllModules();
2266
2267         printf("\nInspIRCd is now running!\n");
2268         if (!nofork)
2269         {
2270                 freopen("/dev/null","w",stdout);
2271                 freopen("/dev/null","w",stderr);
2272         }
2273
2274         /* Add the listening sockets used for client inbound connections
2275          * to the socket engine
2276          */
2277         for (int count = 0; count < portCount; count++)
2278                 SE->AddFd(openSockfd[count],true,X_LISTEN);
2279
2280         WritePID(PID);
2281
2282         /* main loop, this never returns */
2283         for (;;)
2284         {
2285                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2286                  * Once per loop iteration is pleanty.
2287                  */
2288                 OLDTIME = TIME;
2289                 TIME = time(NULL);
2290
2291                 /* Run background module timers every few seconds
2292                  * (the docs say modules shouldnt rely on accurate
2293                  * timing using this event, so we dont have to
2294                  * time this exactly).
2295                  */
2296                 if (((TIME % 8) == 0) && (!expire_run))
2297                 {
2298                         expire_lines();
2299                         FOREACH_MOD OnBackgroundTimer(TIME);
2300                         expire_run = true;
2301                         continue;
2302                 }
2303                 if ((TIME % 8) == 1)
2304                         expire_run = false;
2305                 
2306                 /* Once a second, do the background processing */
2307                 if (TIME != OLDTIME)
2308                         while (DoBackgroundUserStuff(TIME));
2309
2310                 /* Call the socket engine to wait on the active
2311                  * file descriptors. The socket engine has everything's
2312                  * descriptors in its list... dns, modules, users,
2313                  * servers... so its nice and easy, just one call.
2314                  */
2315                 SE->Wait(activefds);
2316
2317                 /**
2318                  * Now process each of the fd's. For users, we have a fast
2319                  * lookup table which can find a user by file descriptor, so
2320                  * processing them by fd isnt expensive. If we have a lot of
2321                  * listening ports or module sockets though, things could get
2322                  * ugly.
2323                  */
2324                 numberactive = activefds.size();
2325                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2326                 {
2327                         int socket_type = SE->GetType(activefds[activefd]);
2328                         switch (socket_type)
2329                         {
2330                                 case X_ESTAB_CLIENT:
2331
2332                                         cu = fd_ref_table[activefds[activefd]];
2333                                         if (cu)
2334                                                 ProcessUser(cu);
2335
2336                                 break;
2337
2338                                 case X_ESTAB_MODULE:
2339
2340                                         /* Process module-owned sockets.
2341                                          * Modules are encouraged to inherit their sockets from
2342                                          * InspSocket so we can process them neatly like this.
2343                                          */
2344                                         s = socket_ref[activefds[activefd]];
2345
2346                                         if ((s) && (!s->Poll()))
2347                                         {
2348                                                 log(DEBUG,"Socket poll returned false, close and bail");
2349                                                 SE->DelFd(s->GetFd());
2350                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2351                                                 {
2352                                                         s_del = (InspSocket*)*a;
2353                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2354                                                         {
2355                                                                 module_sockets.erase(a);
2356                                                                 break;
2357                                                         }
2358                                                 }
2359                                                 s->Close();
2360                                                 delete s;
2361                                         }
2362
2363                                 break;
2364
2365                                 case X_ESTAB_DNS:
2366
2367                                         /* When we are using single-threaded dns,
2368                                          * the sockets for dns end up in our mainloop.
2369                                          * When we are using multi-threaded dns,
2370                                          * each thread has its own basic poll() loop
2371                                          * within it, making them 'fire and forget'
2372                                          * and independent of the mainloop.
2373                                          */
2374 #ifndef THREADED_DNS
2375                                         dns_poll(activefds[activefd]);
2376 #endif
2377                                 break;
2378                                 
2379                                 case X_LISTEN:
2380
2381                                         /* It's a listener */
2382                                         uslen = sizeof(sock_us);
2383                                         length = sizeof(client);
2384                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2385                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2386                                         {
2387                                                 in_port = ntohs(sock_us.sin_port);
2388                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
2389                                                 target = (char*)inet_ntoa(client.sin_addr);
2390                                                 /* Years and years ago, we used to resolve here
2391                                                  * using gethostbyaddr(). That is sucky and we
2392                                                  * don't do that any more...
2393                                                  */
2394                                                 if (incomingSockfd >= 0)
2395                                                 {
2396                                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2397                                                         stats->statsAccept++;
2398                                                         AddClient(incomingSockfd, target, in_port, false, target);
2399                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2400                                                 }
2401                                                 else
2402                                                 {
2403                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2404                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2405                                                         stats->statsRefused++;
2406                                                 }
2407                                         }
2408                                         else
2409                                         {
2410                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2411                                                 shutdown(incomingSockfd,2);
2412                                                 close(incomingSockfd);
2413                                         }
2414                                 break;
2415
2416                                 default:
2417                                         /* Something went wrong if we're in here.
2418                                          * In fact, so wrong, im not quite sure
2419                                          * what we would do, so for now, its going
2420                                          * to safely do bugger all.
2421                                          */
2422                                 break;
2423                         }
2424                 }
2425
2426         }
2427         /* This is never reached -- we hope! */
2428         return 0;
2429 }
2430