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