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