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