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