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