1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
21 #include "inspircd_config.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
32 #include <sys/types.h>
33 #include <sys/event.h>
38 #include <sys/epoll.h>
45 #include <ext/hash_map>
64 #include "inspstring.h"
66 #include "helperfuncs.h"
68 #include "socketengine.h"
71 int LogLevel = DEFAULT;
72 char ServerName[MAXBUF];
74 char ServerDesc[MAXBUF];
75 char AdminName[MAXBUF];
76 char AdminEmail[MAXBUF];
77 char AdminNick[MAXBUF];
79 char restartpass[MAXBUF];
83 char PrefixQuit[MAXBUF];
84 char DieValue[MAXBUF];
85 char DNSServer[MAXBUF];
87 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
88 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
90 time_t startup_time = time(NULL);
91 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
92 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
93 unsigned int SoftLimit = MAXCLIENTS;
94 extern int MaxWhoResults;
98 char DisabledCommands[MAXBUF];
100 bool AllowHalfop = true;
101 bool AllowProtect = true;
102 bool AllowFounder = true;
104 extern std::vector<Module*> modules;
105 std::vector<std::string> module_names;
106 extern std::vector<ircd_module*> factory;
108 std::vector<InspSocket*> module_sockets;
111 int openSockfd[MAXSOCKS];
113 bool unlimitcore = false;
115 time_t TIME = time(NULL), OLDTIME = time(NULL);
125 bool has_been_netsplit = false;
126 extern std::vector<std::string> include_stack;
128 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
129 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
130 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
131 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
132 typedef std::deque<command_t> command_table;
133 typedef std::map<std::string,time_t> autoconnects;
134 typedef std::vector<std::string> servernamelist;
136 // This table references users by file descriptor.
137 // its an array to make it VERY fast, as all lookups are referenced
138 // by an integer, meaning there is no need for a scan/search operation.
139 userrec* fd_ref_table[65536];
141 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
147 user_hash clientlist;
150 command_table cmdlist;
151 autoconnects autoconns;
157 servernamelist servernames;
159 struct linger linger = { 0 };
160 char MyExecutable[1024];
161 int boundPortCount = 0;
162 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
164 char ModPath[MAXBUF];
168 int has_channel(userrec *u, chanrec *c);
169 int usercount(chanrec *c);
170 int usercount_i(chanrec *c);
171 char* Passwd(userrec *user);
172 bool IsDenied(userrec *user);
173 void AddWhoWas(userrec* u);
175 std::stringstream config_f(stringstream::in | stringstream::out);
177 std::vector<userrec*> all_opers;
181 void AddOper(userrec* user)
183 log(DEBUG,"Oper added to optimization list");
184 all_opers.push_back(user);
187 void AddServerName(std::string servername)
189 log(DEBUG,"Adding server name: %s",servername.c_str());
190 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
192 if (*a == servername)
195 servernames.push_back(servername);
198 const char* FindServerNamePtr(std::string servername)
200 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
202 if (*a == servername)
205 AddServerName(servername);
206 return FindServerNamePtr(servername);
209 void DeleteOper(userrec* user)
211 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
215 log(DEBUG,"Oper removed from optimization list");
222 std::string GetRevision()
224 char Revision[] = "$Revision$";
227 char *v2 = strtok_r(s1," ",&savept);
229 v2 = strtok_r(s1," ",&savept);
231 return std::string(v2);
235 std::string getservername()
240 std::string getserverdesc()
245 std::string getnetworkname()
250 std::string getadminname()
255 std::string getadminemail()
260 std::string getadminnick()
265 void ReadConfig(bool bail, userrec* user)
267 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
268 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
270 std::stringstream errstr;
271 include_stack.clear();
273 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
276 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
279 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
287 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
288 while (!errstr.eof())
290 errstr.getline(dataline,1024);
291 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
296 WriteOpers("There were errors in the configuration file:",user->nick);
297 while (!errstr.eof())
299 errstr.getline(dataline,1024);
300 WriteOpers(dataline);
307 ConfValue("server","name",0,ServerName,&config_f);
308 ConfValue("server","description",0,ServerDesc,&config_f);
309 ConfValue("server","network",0,Network,&config_f);
310 ConfValue("admin","name",0,AdminName,&config_f);
311 ConfValue("admin","email",0,AdminEmail,&config_f);
312 ConfValue("admin","nick",0,AdminNick,&config_f);
313 ConfValue("files","motd",0,motd,&config_f);
314 ConfValue("files","rules",0,rules,&config_f);
315 ConfValue("power","diepass",0,diepass,&config_f);
316 ConfValue("power","pause",0,pauseval,&config_f);
317 ConfValue("power","restartpass",0,restartpass,&config_f);
318 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
319 ConfValue("die","value",0,DieValue,&config_f);
320 ConfValue("options","loglevel",0,dbg,&config_f);
321 ConfValue("options","netbuffersize",0,NB,&config_f);
322 ConfValue("options","maxwho",0,MW,&config_f);
323 ConfValue("options","allowhalfop",0,AH,&config_f);
324 ConfValue("options","allowprotect",0,AP,&config_f);
325 ConfValue("options","allowfounder",0,AF,&config_f);
326 ConfValue("dns","server",0,DNSServer,&config_f);
327 ConfValue("dns","timeout",0,DNT,&config_f);
328 ConfValue("options","moduledir",0,ModPath,&config_f);
329 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
330 ConfValue("options","somaxconn",0,MCON,&config_f);
331 ConfValue("options","softlimit",0,SLIMT,&config_f);
333 SoftLimit = atoi(SLIMT);
334 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
336 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
337 SoftLimit = MAXCLIENTS;
339 MaxConn = atoi(MCON);
340 if (MaxConn > SOMAXCONN)
341 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
342 NetBufferSize = atoi(NB);
343 MaxWhoResults = atoi(MW);
344 dns_timeout = atoi(DNT);
350 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
352 strlcpy(ModPath,MOD_PATH,MAXBUF);
353 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
354 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
355 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
356 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
358 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
359 NetBufferSize = 10240;
361 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
363 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
366 if (!strcmp(dbg,"debug"))
368 if (!strcmp(dbg,"verbose"))
370 if (!strcmp(dbg,"default"))
372 if (!strcmp(dbg,"sparse"))
374 if (!strcmp(dbg,"none"))
377 log(DEFAULT,"Reading message of the day...");
378 readfile(RULES,rules);
379 log(DEFAULT,"Reading connect classes...");
381 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
384 ConfValue("connect","allow",i,Value,&config_f);
385 ConfValue("connect","timeout",i,timeout,&config_f);
386 ConfValue("connect","flood",i,flood,&config_f);
387 ConfValue("connect","pingfreq",i,pfreq,&config_f);
388 ConfValue("connect","threshold",i,thold,&config_f);
389 ConfValue("connect","sendq",i,sqmax,&config_f);
390 ConfValue("connect","recvq",i,rqmax,&config_f);
393 strlcpy(c.host,Value,MAXBUF);
395 strlcpy(Value,"",MAXBUF);
396 ConfValue("connect","password",i,Value,&config_f);
397 strlcpy(c.pass,Value,MAXBUF);
398 c.registration_timeout = 90; // default is 2 minutes
400 c.flood = atoi(flood);
402 c.sendqmax = 262144; // 256k
403 c.recvqmax = 4096; // 4k
406 c.threshold = atoi(thold);
410 c.sendqmax = atoi(sqmax);
414 c.recvqmax = atoi(rqmax);
418 c.registration_timeout = atoi(timeout);
422 c.pingtime = atoi(pfreq);
424 Classes.push_back(c);
425 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);
429 ConfValue("connect","deny",i,Value,&config_f);
430 strlcpy(c.host,Value,MAXBUF);
432 Classes.push_back(c);
433 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
437 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
438 read_xline_defaults();
439 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
443 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
445 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
446 ConfValue("link","name",i,Link_ServerName,&config_f);
447 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
448 if (strcmp(Link_AConn,""))
450 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
455 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
458 log(DEFAULT,"Adding and removing modules due to rehash...");
460 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
462 // store the old module names
463 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
465 old_module_names.push_back(*t);
468 // get the new module names
469 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
471 ConfValue("module","name",count2,Value,&config_f);
472 new_module_names.push_back(Value);
475 // now create a list of new modules that are due to be loaded
476 // and a seperate list of modules which are due to be unloaded
477 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
480 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
486 added_modules.push_back(*_new);
488 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
491 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
497 removed_modules.push_back(*oldm);
499 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
501 int rem = 0, add = 0;
502 if (!removed_modules.empty())
503 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
505 if (UnloadModule(removing->c_str()))
507 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
508 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
513 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
516 if (!added_modules.empty())
517 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
519 if (LoadModule(adding->c_str()))
521 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
522 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
527 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
530 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());
535 /* add a channel to a user, creating the record for it if needed and linking
536 * it to the user record */
538 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
540 if ((!user) || (!cn))
542 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
550 strncpy(cname,cn,MAXBUF);
552 // we MUST declare this wherever we use FOREACH_RESULT
555 if (strlen(cname) > CHANMAX)
557 cname[CHANMAX] = '\0';
560 log(DEBUG,"add_channel: %s %s",user->nick,cname);
562 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
564 return NULL; // already on the channel!
568 if (!FindChan(cname))
571 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
572 if (MOD_RESULT == 1) {
576 /* create a new one */
577 log(DEBUG,"add_channel: creating: %s",cname);
579 chanlist[cname] = new chanrec();
581 strlcpy(chanlist[cname]->name, cname,CHANMAX);
582 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
583 chanlist[cname]->created = TIME;
584 strcpy(chanlist[cname]->topic, "");
585 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
586 chanlist[cname]->topicset = 0;
587 Ptr = chanlist[cname];
588 log(DEBUG,"add_channel: created: %s",cname);
589 /* set created to 2 to indicate user
590 * is the first in the channel
591 * and should be given ops */
597 /* channel exists, just fish out a pointer to its struct */
598 Ptr = FindChan(cname);
601 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
603 // the override flag allows us to bypass channel modes
604 // and bans (used by servers)
605 if ((!override) || (!strcasecmp(user->server,ServerName)))
607 log(DEBUG,"Not overriding...");
609 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
610 if (MOD_RESULT == 1) {
613 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
617 log(DEBUG,"add_channel: checking key, invite, etc");
619 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
624 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
627 log(DEBUG,"add_channel: no key given in JOIN");
628 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
633 if (strcasecmp(key,Ptr->key))
635 log(DEBUG,"add_channel: bad key given in JOIN");
636 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
641 log(DEBUG,"add_channel: no key");
644 FOREACH_RESULT(OnCheckInvite(user, Ptr));
647 if (Ptr->binarymodes & CM_INVITEONLY)
649 log(DEBUG,"add_channel: channel is +i");
650 if (user->IsInvited(Ptr->name))
652 /* user was invited to channel */
653 /* there may be an optional channel NOTICE here */
657 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
661 log(DEBUG,"add_channel: channel is not +i");
664 FOREACH_RESULT(OnCheckLimit(user, Ptr));
669 if (usercount(Ptr) >= Ptr->limit)
671 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
676 log(DEBUG,"add_channel: about to walk banlist");
678 FOREACH_RESULT(OnCheckBan(user, Ptr));
681 /* check user against the channel banlist */
684 if (Ptr->bans.size())
686 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
688 if (match(user->GetFullHost(),i->data))
690 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
696 log(DEBUG,"add_channel: bans checked");
704 user->RemoveInvite(Ptr->name);
707 log(DEBUG,"add_channel: invites removed");
712 log(DEBUG,"Overridden checks");
720 log(DEBUG,"Passed channel checks");
722 for (int index =0; index != MAXCHANS; index++)
724 log(DEBUG,"Check location %d",index);
725 if (user->chans[index].channel == NULL)
727 log(DEBUG,"Adding into their channel list at location %d",index);
731 /* first user in is given ops */
732 user->chans[index].uc_modes = UCMODE_OP;
736 user->chans[index].uc_modes = 0;
738 user->chans[index].channel = Ptr;
739 Ptr->AddUser((char*)user);
740 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
742 log(DEBUG,"Sent JOIN to client");
746 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
747 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
750 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
751 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
752 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
753 FOREACH_MOD OnUserJoin(user,Ptr);
757 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
758 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
762 /* remove a channel from a users record, and remove the record from memory
763 * if the channel has become empty */
765 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
767 if ((!user) || (!cname))
769 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
775 if ((!cname) || (!user))
780 Ptr = FindChan(cname);
787 FOREACH_MOD OnUserPart(user,Ptr);
788 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
790 for (int i =0; i != MAXCHANS; i++)
792 /* zap it from the channel list of the user */
793 if (user->chans[i].channel == Ptr)
797 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
801 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
803 user->chans[i].uc_modes = 0;
804 user->chans[i].channel = NULL;
805 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
810 Ptr->DelUser((char*)user);
812 /* if there are no users left on the channel */
815 chan_hash::iterator iter = chanlist.find(Ptr->name);
817 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
819 /* kill the record */
820 if (iter != chanlist.end())
822 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
824 chanlist.erase(iter);
832 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
834 if ((!src) || (!user) || (!Ptr) || (!reason))
836 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
840 if ((!Ptr) || (!user) || (!src))
845 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
847 if (!has_channel(user,Ptr))
849 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
854 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
855 if (MOD_RESULT == ACR_DENY)
858 if (MOD_RESULT == ACR_DEFAULT)
860 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
862 if (cstatus(src,Ptr) == STATUS_HOP)
864 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
868 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
876 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
880 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
882 for (int i =0; i != MAXCHANS; i++)
884 /* zap it from the channel list of the user */
885 if (user->chans[i].channel)
886 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
888 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
889 user->chans[i].uc_modes = 0;
890 user->chans[i].channel = NULL;
891 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
896 Ptr->DelUser((char*)user);
898 /* if there are no users left on the channel */
901 chan_hash::iterator iter = chanlist.find(Ptr->name);
903 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
905 /* kill the record */
906 if (iter != chanlist.end())
908 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
910 chanlist.erase(iter);
918 /* This function pokes and hacks at a parameter list like the following:
920 * PART #winbot,#darkgalaxy :m00!
922 * to turn it into a series of individual calls like this:
925 * PART #darkgalaxy :m00!
927 * The seperate calls are sent to a callback function provided by the caller
928 * (the caller will usually call itself recursively). The callback function
929 * must be a command handler. Calling this function on a line with no list causes
930 * no action to be taken. You must provide a starting and ending parameter number
931 * where the range of the list can be found, useful if you have a terminating
932 * parameter as above which is actually not part of the list, or parameters
933 * before the actual list as well. This code is used by many functions which
934 * can function as "one to list" (see the RFC) */
936 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
941 char blog[32][MAXBUF];
942 char blog2[32][MAXBUF];
943 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
947 for (int i = 0; i <32; i++)
950 for (int i = 0; i <32; i++)
954 for (int i = 0; i <10; i++)
963 if (pcnt > 1) /* we have a key to copy */
965 strlcpy(keystr,parameters[1],MAXBUF);
969 if (!parameters[start])
973 if (!strchr(parameters[start],','))
978 for (int i = start; i <= end; i++)
982 strlcat(plist,parameters[i],MAXBUF);
990 for (int i = 0; i < t; i++)
995 strlcpy(blog[j++],param,MAXBUF);
999 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1004 strlcpy(blog[j++],param,MAXBUF);
1007 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1012 if ((joins) && (keystr))
1014 if (strchr(keystr,','))
1018 t2 = strlen(keystr);
1019 for (int i = 0; i < t2; i++)
1021 if (keystr[i] == ',')
1024 strlcpy(blog2[j++],param,MAXBUF);
1028 strlcpy(blog2[j++],param,MAXBUF);
1033 for (j = 0; j < total; j++)
1039 for (q = end; q < pcnt-1; q++)
1041 if (parameters[q+1])
1043 pars[q-end+1] = parameters[q+1];
1046 if ((joins) && (parameters[1]))
1057 /* repeatedly call the function with the hacked parameter list */
1058 if ((joins) && (pcnt > 1))
1062 // pars[1] already set up and containing key from blog2[j]
1067 pars[1] = parameters[1];
1073 fn(pars,pcnt-(end-start),u);
1082 void kill_link(userrec *user,const char* r)
1084 user_hash::iterator iter = clientlist.find(user->nick);
1086 char reason[MAXBUF];
1088 strncpy(reason,r,MAXBUF);
1090 if (strlen(reason)>MAXQUIT)
1092 reason[MAXQUIT-1] = '\0';
1095 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1096 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1097 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1099 if (user->registered == 7) {
1100 FOREACH_MOD OnUserQuit(user,reason);
1101 WriteCommonExcept(user,"QUIT :%s",reason);
1104 user->FlushWriteBuf();
1106 FOREACH_MOD OnUserDisconnect(user);
1110 FOREACH_MOD OnRawSocketClose(user->fd);
1112 user->CloseSocket();
1115 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1116 // if they were an oper with +s.
1117 if (user->registered == 7) {
1118 purge_empty_chans(user);
1119 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1120 if (!strcmp(user->server,ServerName))
1121 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1125 if (iter != clientlist.end())
1127 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1129 fd_ref_table[user->fd] = NULL;
1130 clientlist.erase(iter);
1135 void kill_link_silent(userrec *user,const char* r)
1137 user_hash::iterator iter = clientlist.find(user->nick);
1139 char reason[MAXBUF];
1141 strncpy(reason,r,MAXBUF);
1143 if (strlen(reason)>MAXQUIT)
1145 reason[MAXQUIT-1] = '\0';
1148 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1149 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1150 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1152 user->FlushWriteBuf();
1154 if (user->registered == 7) {
1155 FOREACH_MOD OnUserQuit(user,reason);
1156 WriteCommonExcept(user,"QUIT :%s",reason);
1159 FOREACH_MOD OnUserDisconnect(user);
1163 FOREACH_MOD OnRawSocketClose(user->fd);
1165 user->CloseSocket();
1168 if (user->registered == 7) {
1169 purge_empty_chans(user);
1172 if (iter != clientlist.end())
1174 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1176 fd_ref_table[user->fd] = NULL;
1177 clientlist.erase(iter);
1183 int main(int argc, char** argv)
1187 log(DEBUG,"*** InspIRCd starting up!");
1188 if (!FileExists(CONFIG_FILE))
1190 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1191 log(DEFAULT,"main: no config");
1192 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1196 for (int i = 1; i < argc; i++)
1198 if (!strcmp(argv[i],"-nofork")) {
1201 if (!strcmp(argv[i],"-wait")) {
1204 if (!strcmp(argv[i],"-nolimit")) {
1209 strlcpy(MyExecutable,argv[0],MAXBUF);
1211 // initialize the lowercase mapping table
1212 for (unsigned int cn = 0; cn < 256; 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)'\\'] = '|';
1222 if (InspIRCd(argv,argc) == ERROR)
1224 log(DEFAULT,"main: daemon function bailed");
1225 printf("ERROR: could not initialise. Shutting down.\n");
1232 template<typename T> inline string ConvToStr(const T &in)
1235 if (!(tmp << in)) return string();
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 */
1242 userrec* ReHashNick(char* Old, char* New)
1244 //user_hash::iterator newnick;
1245 user_hash::iterator oldnick = clientlist.find(Old);
1247 log(DEBUG,"ReHashNick: %s %s",Old,New);
1249 if (!strcasecmp(Old,New))
1251 log(DEBUG,"old nick is new nick, skipping");
1252 return oldnick->second;
1255 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1257 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1259 userrec* olduser = oldnick->second;
1260 clientlist[New] = olduser;
1261 clientlist.erase(oldnick);
1263 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1265 return clientlist[New];
1268 /* adds or updates an entry in the whowas list */
1269 void AddWhoWas(userrec* u)
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;
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
1286 if (iter == whowas.end())
1288 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1290 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1292 // 3600 seconds in an hour ;)
1293 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1295 // delete the old one
1296 if (i->second) delete i->second;
1297 // replace with new one
1299 log(DEBUG,"added WHOWAS entry, purged an old record");
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");
1309 log(DEBUG,"added fresh WHOWAS entry");
1310 whowas[a->nick] = a;
1315 log(DEBUG,"updated WHOWAS entry");
1316 if (iter->second) delete iter->second;
1322 /* add a client connection to the sockets list */
1323 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1327 user_hash::iterator iter;
1329 tempnick = ConvToStr(socket) + "-unknown";
1330 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1332 iter = clientlist.find(tempnick);
1335 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1336 // using one as a registered connection. As theyre per fd, we can also safely assume
1337 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1338 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1339 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1340 // issue in earlier alphas/betas
1341 if (iter != clientlist.end())
1343 userrec* goner = iter->second;
1345 clientlist.erase(iter);
1349 * It is OK to access the value here this way since we know
1350 * it exists, we just created it above.
1352 * At NO other time should you access a value in a map or a
1353 * hash_map this way.
1355 clientlist[tempnick] = new userrec();
1357 NonBlocking(socket);
1358 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1360 clientlist[tempnick]->fd = socket;
1361 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1362 strlcpy(clientlist[tempnick]->host, host,160);
1363 strlcpy(clientlist[tempnick]->dhost, host,160);
1364 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1365 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1366 clientlist[tempnick]->registered = 0;
1367 clientlist[tempnick]->signon = TIME+dns_timeout;
1368 clientlist[tempnick]->lastping = 1;
1369 clientlist[tempnick]->port = port;
1370 strlcpy(clientlist[tempnick]->ip,ip,16);
1372 // set the registration timeout for this user
1373 unsigned long class_regtimeout = 90;
1374 int class_flood = 0;
1375 long class_threshold = 5;
1376 long class_sqmax = 262144; // 256kb
1377 long class_rqmax = 4096; // 4k
1379 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1381 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1383 class_regtimeout = (unsigned long)i->registration_timeout;
1384 class_flood = i->flood;
1385 clientlist[tempnick]->pingmax = i->pingtime;
1386 class_threshold = i->threshold;
1387 class_sqmax = i->sendqmax;
1388 class_rqmax = i->recvqmax;
1393 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1394 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1395 clientlist[tempnick]->flood = class_flood;
1396 clientlist[tempnick]->threshold = class_threshold;
1397 clientlist[tempnick]->sendqmax = class_sqmax;
1398 clientlist[tempnick]->recvqmax = class_rqmax;
1400 for (int i = 0; i < MAXCHANS; i++)
1402 clientlist[tempnick]->chans[i].channel = NULL;
1403 clientlist[tempnick]->chans[i].uc_modes = 0;
1406 if (clientlist.size() > SoftLimit)
1408 kill_link(clientlist[tempnick],"No more connections allowed");
1412 if (clientlist.size() >= MAXCLIENTS)
1414 kill_link(clientlist[tempnick],"No more connections allowed");
1418 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1419 // its a pretty big but for the moment valid assumption:
1420 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1421 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1422 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1423 // which for the time being is a physical impossibility (even the largest networks dont have more
1424 // than about 10,000 users on ONE server!)
1425 if ((unsigned)socket > 65534)
1427 kill_link(clientlist[tempnick],"Server is full");
1432 char* e = matches_exception(ip);
1435 char* r = matches_zline(ip);
1438 char reason[MAXBUF];
1439 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1440 kill_link(clientlist[tempnick],reason);
1444 fd_ref_table[socket] = clientlist[tempnick];
1448 /* shows the message of the day, and any other on-logon stuff */
1449 void FullConnectUser(userrec* user)
1452 user->idle_lastmsg = TIME;
1453 log(DEBUG,"ConnectUser: %s",user->nick);
1455 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1457 kill_link(user,"Invalid password");
1462 kill_link(user,"Unauthorised connection");
1466 char match_against[MAXBUF];
1467 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1468 char* e = matches_exception(match_against);
1471 char* r = matches_gline(match_against);
1474 char reason[MAXBUF];
1475 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1476 kill_link_silent(user,reason);
1479 r = matches_kline(user->host);
1482 char reason[MAXBUF];
1483 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1484 kill_link_silent(user,reason);
1489 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1490 user->registered = 7;
1492 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1493 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1494 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1495 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1496 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1497 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1498 std::stringstream v;
1499 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1500 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1501 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1503 std::string data005 = v.str();
1504 FOREACH_MOD On005Numeric(data005);
1505 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1506 // so i'd better split it :)
1507 std::stringstream out(data005);
1508 std::string token = "";
1509 std::string line5 = "";
1510 int token_counter = 0;
1514 line5 = line5 + token + " ";
1516 if ((token_counter >= 13) || (out.eof() == true))
1518 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1525 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1526 FOREACH_MOD OnUserConnect(user);
1527 FOREACH_MOD OnGlobalConnect(user);
1528 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1532 /* shows the message of the day, and any other on-logon stuff */
1533 void ConnectUser(userrec *user)
1535 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1536 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1538 FullConnectUser(user);
1542 std::string GetVersionString()
1544 char Revision[] = "$Revision$";
1545 char versiondata[MAXBUF];
1546 char *s1 = Revision;
1548 char *v2 = strtok_r(s1," ",&savept);
1550 v2 = strtok_r(s1," ",&savept);
1552 char socketengine[] = engine_name;
1553 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1557 void handle_version(char **parameters, int pcnt, userrec *user)
1559 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1563 // calls a handler function for a command
1565 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1567 for (unsigned int i = 0; i < cmdlist.size(); i++)
1569 if (!strcasecmp(cmdlist[i].command,commandname))
1571 if (cmdlist[i].handler_function)
1573 if (pcnt>=cmdlist[i].min_params)
1575 if (strchr(user->modes,cmdlist[i].flags_needed))
1577 cmdlist[i].handler_function(parameters,pcnt,user);
1586 void force_nickchange(userrec* user,const char* newnick)
1593 FOREACH_RESULT(OnUserPreNick(user,newnick));
1596 kill_link(user,"Nickname collision");
1599 if (matches_qline(newnick))
1602 kill_link(user,"Nickname collision");
1610 strncpy(nick,newnick,MAXBUF);
1612 if (user->registered == 7)
1616 handle_nick(pars,1,user);
1622 int process_parameters(char **command_p,char *parameters)
1625 int q = strlen(parameters);
1628 /* no parameters, command_p invalid! */
1631 if (parameters[0] == ':')
1633 command_p[0] = parameters+1;
1638 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1640 /* only one parameter */
1641 command_p[0] = parameters;
1642 if (parameters[0] == ':')
1644 if (strchr(parameters,' ') != NULL)
1652 command_p[j++] = parameters;
1653 for (int i = 0; i <= q; i++)
1655 if (parameters[i] == ' ')
1657 command_p[j++] = parameters+i+1;
1658 parameters[i] = '\0';
1659 if (command_p[j-1][0] == ':')
1661 *command_p[j-1]++; /* remove dodgy ":" */
1663 /* parameter like this marks end of the sequence */
1667 return j; /* returns total number of items in the list */
1670 void process_command(userrec *user, char* cmd)
1674 char *command_p[127];
1675 char p[MAXBUF], temp[MAXBUF];
1676 int j, items, cmd_found;
1678 for (int i = 0; i < 127; i++)
1679 command_p[i] = NULL;
1694 int total_params = 0;
1697 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1699 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1702 // found a 'trailing', we dont count them after this.
1710 // another phidjit bug...
1711 if (total_params > 126)
1713 *(strchr(cmd,' ')) = '\0';
1714 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1718 strlcpy(temp,cmd,MAXBUF);
1720 std::string tmp = cmd;
1721 for (int i = 0; i <= MODCOUNT; i++)
1723 std::string oldtmp = tmp;
1724 modules[i]->OnServerRaw(tmp,true,user);
1727 log(DEBUG,"A Module changed the input string!");
1728 log(DEBUG,"New string: %s",tmp.c_str());
1729 log(DEBUG,"Old string: %s",oldtmp.c_str());
1733 strlcpy(cmd,tmp.c_str(),MAXBUF);
1734 strlcpy(temp,cmd,MAXBUF);
1736 if (!strchr(cmd,' '))
1738 /* no parameters, lets skip the formalities and not chop up
1740 log(DEBUG,"About to preprocess command with no params");
1742 command_p[0] = NULL;
1744 for (unsigned int i = 0; i <= strlen(cmd); i++)
1746 cmd[i] = toupper(cmd[i]);
1754 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1755 for (unsigned int i = 0; i < strlen(temp); i++)
1757 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1763 /* split the full string into a command plus parameters */
1767 if (strchr(cmd,' '))
1769 for (unsigned int i = 0; i <= strlen(cmd); i++)
1771 /* capitalise the command ONLY, leave params intact */
1772 cmd[i] = toupper(cmd[i]);
1773 /* are we nearly there yet?! :P */
1777 parameters = cmd+i+1;
1785 for (unsigned int i = 0; i <= strlen(cmd); i++)
1787 cmd[i] = toupper(cmd[i]);
1794 if (strlen(command)>MAXCOMMAND)
1796 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1800 for (unsigned int x = 0; x < strlen(command); x++)
1802 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1804 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1806 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1809 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1816 for (unsigned int i = 0; i != cmdlist.size(); i++)
1818 if (cmdlist[i].command[0])
1820 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1826 items = process_parameters(command_p,parameters);
1831 command_p[0] = NULL;
1837 command_p[0] = NULL;
1842 /* activity resets the ping pending timer */
1843 user->nping = TIME + user->pingmax;
1844 if ((items) < cmdlist[i].min_params)
1846 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1847 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1850 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1852 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1853 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1857 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1859 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1860 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1864 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1866 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1868 if ((!isnick(user->nick)) || (user->registered != 7))
1870 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1871 WriteServ(user->fd,"451 %s :You have not registered",command);
1875 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1877 std::stringstream dcmds(DisabledCommands);
1878 while (!dcmds.eof())
1880 std::string thiscmd;
1882 if (!strcasecmp(thiscmd.c_str(),command))
1884 // command is disabled!
1885 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1890 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1892 if (cmdlist[i].handler_function)
1895 /* ikky /stats counters */
1898 cmdlist[i].use_count++;
1899 cmdlist[i].total_bytes+=strlen(temp);
1903 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1904 if (MOD_RESULT == 1) {
1908 /* WARNING: nothing may come after the
1909 * command handler call, as the handler
1910 * may free the user structure! */
1912 cmdlist[i].handler_function(command_p,items,user);
1918 WriteServ(user->fd,"451 %s :You have not registered",command);
1926 if ((!cmd_found) && (user))
1929 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1933 bool removecommands(const char* source)
1935 bool go_again = true;
1939 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1941 if (!strcmp(i->source,source))
1943 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1954 void process_buffer(const char* cmdbuf,userrec *user)
1958 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1964 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1971 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1973 strlcpy(cmd,cmdbuf,MAXBUF);
1978 int sl = strlen(cmd)-1;
1979 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1984 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1989 while (cmd[sl] == ' ') // strip trailing spaces
1999 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2001 if ((user) && (cmd))
2003 process_command(user,cmd);
2007 char MODERR[MAXBUF];
2014 void erase_factory(int j)
2017 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2022 factory.push_back(NULL);
2029 void erase_module(int j)
2032 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2038 modules.push_back(NULL);
2044 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2048 module_names.erase(v);
2056 bool UnloadModule(const char* filename)
2058 std::string filename_str = filename;
2059 for (unsigned int j = 0; j != module_names.size(); j++)
2061 if (module_names[j] == filename_str)
2063 if (modules[j]->GetVersion().Flags & VF_STATIC)
2065 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2066 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2069 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2071 log(DEBUG,"Deleting module...");
2073 log(DEBUG,"Erasing module entry...");
2075 log(DEBUG,"Removing dependent commands...");
2076 removecommands(filename);
2077 log(DEFAULT,"Module %s unloaded",filename);
2082 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2083 snprintf(MODERR,MAXBUF,"Module not loaded");
2087 bool LoadModule(const char* filename)
2089 char modfile[MAXBUF];
2091 snprintf(modfile,MAXBUF,"%s",filename);
2093 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2095 std::string filename_str = filename;
2097 if (!DirValid(modfile))
2099 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2100 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2104 log(DEBUG,"Loading module: %s",modfile);
2106 if (FileExists(modfile))
2109 for (unsigned int j = 0; j < module_names.size(); j++)
2111 if (module_names[j] == filename_str)
2113 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2114 snprintf(MODERR,MAXBUF,"Module already loaded");
2118 ircd_module* a = new ircd_module(modfile);
2119 factory[MODCOUNT+1] = a;
2120 if (factory[MODCOUNT+1]->LastError())
2122 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2123 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2127 if (factory[MODCOUNT+1]->factory)
2129 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2130 modules[MODCOUNT+1] = m;
2131 /* save the module and the module's classfactory, if
2132 * this isnt done, random crashes can occur :/ */
2133 module_names.push_back(filename);
2137 log(DEFAULT,"Unable to load %s",modfile);
2138 snprintf(MODERR,MAXBUF,"Factory function failed!");
2145 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2146 snprintf(MODERR,MAXBUF,"Module file could not be found");
2151 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2156 int InspIRCd(char** argv, int argc)
2158 struct sockaddr_in client,server;
2159 char addrs[MAXBUF][255];
2160 int incomingSockfd, result = TRUE;
2164 int selectResult = 0, selectResult2 = 0;
2167 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2170 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2171 log_file = fopen(logpath.c_str(),"a+");
2174 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2179 printf("Logging to ircd.log...\n");
2181 printf("Logging to %s...\n",logpath.c_str());
2184 log(DEFAULT,"$Id$");
2187 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2189 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2191 SetupCommandTable();
2192 log(DEBUG,"InspIRCd: startup: default command table set up");
2194 ReadConfig(true,NULL);
2197 printf("WARNING: %s\n\n",DieValue);
2198 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2201 log(DEBUG,"InspIRCd: startup: read config");
2203 AddServerName(ServerName);
2205 int clientportcount = 0;
2207 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2209 ConfValue("bind","port",count,configToken,&config_f);
2210 ConfValue("bind","address",count,Addr,&config_f);
2211 ConfValue("bind","type",count,Type,&config_f);
2212 if (!strcmp(Type,"servers"))
2214 // modules handle this bind type now.
2218 ports[clientportcount] = atoi(configToken);
2219 strlcpy(addrs[clientportcount],Addr,256);
2222 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2224 portCount = clientportcount;
2226 log(DEBUG,"InspIRCd: startup: read %lu total client ports",(unsigned long)portCount);
2227 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2231 /* BugFix By Craig! :p */
2233 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2235 ConfValue("module","name",count,configToken,&config_f);
2236 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2237 if (!LoadModule(configToken))
2239 log(DEFAULT,"Exiting due to a module loader error.");
2240 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2244 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2246 startup_time = time(NULL);
2249 ConfValue("pid","file",0,PID,&config_f);
2250 // write once here, to try it out and make sure its ok
2253 /* setup select call */
2255 FD_ZERO(&selectFds);
2257 log(DEBUG,"InspIRCd: startup: zero selects");
2258 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2260 for (count = 0; count < portCount; count++)
2262 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2264 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2267 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2269 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2271 else /* well we at least bound to one socket so we'll continue */
2277 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2279 /* if we didn't bind to anything then abort */
2280 if (boundPortCount == 0)
2282 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2283 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2288 printf("\nInspIRCd is now running!\n");
2292 log(VERBOSE,"Not forking as -nofork was specified");
2296 if (DaemonSeed() == ERROR)
2298 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2299 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2309 length = sizeof (client);
2312 tvs.tv_usec = 10000L;
2315 tv.tv_usec = 10000L;
2318 tval.tv_usec = 10000L;
2320 int total_in_this_set = 0;
2321 int i = 0, v = 0, j = 0, cycle_iter = 0;
2322 bool expire_run = false;
2324 cycle_iter = i = j = 0; // stop the compiler whining - these may be marked unused in certain socket engine types
2326 /* main loop, this never returns */
2329 #ifdef _POSIX_PRIORITY_SCHEDULING
2335 // we only read time() once per iteration rather than tons of times!
2341 unsigned int numsockets = module_sockets.size();
2342 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2344 InspSocket* s = (InspSocket*)*a;
2345 if ((s) && (!s->Poll()))
2347 log(DEBUG,"Socket poll returned false, close and bail");
2349 module_sockets.erase(a);
2353 // we gained a socket, sarper
2354 if (module_sockets.size() != numsockets) break;
2357 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2358 // them in a list, then reap the list every second or so.
2359 if (((TIME % 5) == 0) && (!expire_run))
2362 FOREACH_MOD OnBackgroundTimer(TIME);
2366 if ((TIME % 5) == 1)
2369 // fix by brain - this must be below any manipulation of the hashmap by modules
2370 user_hash::iterator count2 = clientlist.begin();
2373 while (count2 != clientlist.end())
2379 total_in_this_set = 0;
2381 user_hash::iterator xcount = count2;
2382 user_hash::iterator endingiter = count2;
2384 if (count2 == clientlist.end()) break;
2386 userrec* curr = NULL;
2389 curr = count2->second;
2391 if ((long)curr == -1)
2394 if ((curr) && (curr->fd != 0))
2396 #ifdef _POSIX_PRIORITY_SCHEDULING
2399 // assemble up to 64 sockets into an fd_set
2400 // to implement a pooling mechanism.
2402 // This should be up to 64x faster than the
2403 // old implementation.
2405 while (total_in_this_set < 1024)
2407 if (count2 != clientlist.end())
2409 curr = count2->second;
2410 if ((long)curr == -1)
2412 int currfd = curr->fd;
2413 // we don't check the state of remote users.
2414 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2416 curr->FlushWriteBuf();
2417 if (curr->GetWriteError() != "")
2419 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2420 kill_link(curr,curr->GetWriteError().c_str());
2424 FD_SET (curr->fd, &sfd);
2426 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2427 // their connection class.
2428 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2430 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2431 kill_link(curr,"Registration timeout");
2434 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2436 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
2437 curr->dns_done = true;
2439 FullConnectUser(curr);
2440 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2443 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
2445 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2446 FullConnectUser(curr);
2447 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2450 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2452 if ((!curr->lastping) && (curr->registered == 7))
2454 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2455 kill_link(curr,"Ping timeout");
2458 Write(curr->fd,"PING :%s",ServerName);
2459 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2461 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2465 total_in_this_set++;
2469 endingiter = count2;
2470 count2 = xcount; // roll back to where we were
2472 // KQUEUE and EPOLL: We don't go through a loop to fill the fd_set so instead we must manually do this loop every now and again.
2473 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
2475 if (cycle_iter > 20) while (count2 != clientlist.end())
2478 if (count2 != clientlist.end())
2480 curr = count2->second;
2481 if ((long)curr == -1)
2483 int currfd = curr->fd;
2484 // we don't check the state of remote users.
2485 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2487 curr->FlushWriteBuf();
2488 if (curr->GetWriteError() != "")
2490 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2491 kill_link(curr,curr->GetWriteError().c_str());
2495 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2496 // their connection class.
2497 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2499 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2500 kill_link(curr,"Registration timeout");
2504 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2506 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
2507 curr->dns_done = true;
2509 FullConnectUser(curr);
2510 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2513 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2515 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2516 FullConnectUser(curr);
2517 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2520 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2522 if ((!curr->lastping) && (curr->registered == 7))
2524 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2525 kill_link(curr,"Ping timeout");
2528 Write(curr->fd,"PING :%s",ServerName);
2529 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2531 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2538 // increment the counter right to the end of the list, as kqueue processes everything in one go
2544 #ifdef _POSIX_PRIORITY_SCHEDULING
2550 log(DEBUG,"Data waiting on socket %d",cu->fd);
2553 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
2556 result = cu->ReadData(data, 65535);
2560 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
2563 log(DEBUG,"Read result: %d",result);
2566 statsRecv += result;
2567 // perform a check on the raw buffer as an array (not a string!) to remove
2568 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
2569 // hopefully this should stop even more people whining about "Unknown command: *"
2570 for (int checker = 0; checker < result; checker++)
2572 if ((data[checker] == 0) || (data[checker] == 7))
2573 data[checker] = ' ';
2576 data[result] = '\0';
2577 userrec* current = cu;
2578 int currfd = current->fd;
2580 // add the data to the users buffer
2582 if (!current->AddBuffer(data))
2584 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
2585 if (current->registered == 7)
2587 kill_link(current,"RecvQ exceeded");
2591 WriteOpers("*** Excess flood from %s",current->ip);
2592 log(DEFAULT,"Excess flood from: %s",current->ip);
2593 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2598 if (current->recvq.length() > (unsigned)NetBufferSize)
2600 if (current->registered == 7)
2602 kill_link(current,"RecvQ exceeded");
2606 WriteOpers("*** Excess flood from %s",current->ip);
2607 log(DEFAULT,"Excess flood from: %s",current->ip);
2608 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2613 // while there are complete lines to process...
2614 while (current->BufferIsReady())
2617 if (TIME > current->reset_due)
2619 current->reset_due = TIME + current->threshold;
2620 current->lines_in = 0;
2622 current->lines_in++;
2623 if (current->lines_in > current->flood)
2625 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2626 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2627 kill_link(current,"Excess flood");
2630 if ((floodlines > current->flood) && (current->flood != 0))
2632 if (current->registered == 7)
2634 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2635 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2636 kill_link(current,"Excess flood");
2640 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2645 char sanitized[MAXBUF];
2646 // use GetBuffer to copy single lines into the sanitized string
2647 std::string single_line = current->GetBuffer();
2648 current->bytes_in += single_line.length();
2650 if (single_line.length()>512)
2652 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2653 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2654 kill_link(current,"Excess flood");
2657 strlcpy(sanitized,single_line.c_str(),MAXBUF);
2660 userrec* old_comp = fd_ref_table[currfd];
2661 // we're gonna re-scan to check if the nick is gone, after every
2662 // command - if it has, we're gonna bail
2663 process_buffer(sanitized,current);
2664 // look for the user's record in case it's changed... if theyve quit,
2665 // we cant do anything more with their buffer, so bail.
2666 // there used to be an ugly, slow loop here. Now we have a reference
2667 // table, life is much easier (and FASTER)
2668 userrec* new_comp = fd_ref_table[currfd];
2669 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
2677 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
2679 log(DEBUG,"killing: %s",cu->nick);
2680 kill_link(cu,strerror(errno));
2684 // result EAGAIN means nothing read
2685 if (result == EAGAIN)
2693 else if (result > 0)
2698 for (int q = 0; q < total_in_this_set; q++)
2704 #ifdef _POSIX_PRIORITY_SCHEDULING
2710 char target[MAXBUF], resolved[MAXBUF];
2711 length = sizeof (client);
2712 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2713 log(DEBUG,"Accepted socket %d",incomingSockfd);
2715 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2716 strlcpy (resolved, target, MAXBUF);
2718 if (incomingSockfd < 0)
2720 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
2721 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
2726 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
2728 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
2729 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2736 #ifdef _POSIX_PRIORITY_SCHEDULING
2742 close (incomingSockfd);