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