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