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