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)
208 void DeleteOper(userrec* user)
210 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
214 log(DEBUG,"Oper removed from optimization list");
221 std::string GetRevision()
223 char Revision[] = "$Revision$";
226 char *v2 = strtok_r(s1," ",&savept);
228 v2 = strtok_r(s1," ",&savept);
230 return std::string(v2);
234 std::string getservername()
239 std::string getserverdesc()
244 std::string getnetworkname()
249 std::string getadminname()
254 std::string getadminemail()
259 std::string getadminnick()
264 void ReadConfig(bool bail, userrec* user)
266 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
267 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
269 std::stringstream errstr;
270 include_stack.clear();
272 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
275 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
278 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
286 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
287 while (!errstr.eof())
289 errstr.getline(dataline,1024);
290 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
295 WriteOpers("There were errors in the configuration file:",user->nick);
296 while (!errstr.eof())
298 errstr.getline(dataline,1024);
299 WriteOpers(dataline);
306 ConfValue("server","name",0,ServerName,&config_f);
307 ConfValue("server","description",0,ServerDesc,&config_f);
308 ConfValue("server","network",0,Network,&config_f);
309 ConfValue("admin","name",0,AdminName,&config_f);
310 ConfValue("admin","email",0,AdminEmail,&config_f);
311 ConfValue("admin","nick",0,AdminNick,&config_f);
312 ConfValue("files","motd",0,motd,&config_f);
313 ConfValue("files","rules",0,rules,&config_f);
314 ConfValue("power","diepass",0,diepass,&config_f);
315 ConfValue("power","pause",0,pauseval,&config_f);
316 ConfValue("power","restartpass",0,restartpass,&config_f);
317 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
318 ConfValue("die","value",0,DieValue,&config_f);
319 ConfValue("options","loglevel",0,dbg,&config_f);
320 ConfValue("options","netbuffersize",0,NB,&config_f);
321 ConfValue("options","maxwho",0,MW,&config_f);
322 ConfValue("options","allowhalfop",0,AH,&config_f);
323 ConfValue("options","allowprotect",0,AP,&config_f);
324 ConfValue("options","allowfounder",0,AF,&config_f);
325 ConfValue("dns","server",0,DNSServer,&config_f);
326 ConfValue("dns","timeout",0,DNT,&config_f);
327 ConfValue("options","moduledir",0,ModPath,&config_f);
328 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
329 ConfValue("options","somaxconn",0,MCON,&config_f);
330 ConfValue("options","softlimit",0,SLIMT,&config_f);
332 SoftLimit = atoi(SLIMT);
333 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
335 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
336 SoftLimit = MAXCLIENTS;
338 MaxConn = atoi(MCON);
339 if (MaxConn > SOMAXCONN)
340 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
341 NetBufferSize = atoi(NB);
342 MaxWhoResults = atoi(MW);
343 dns_timeout = atoi(DNT);
349 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
351 strlcpy(ModPath,MOD_PATH,MAXBUF);
352 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
353 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
354 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
355 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
357 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
358 NetBufferSize = 10240;
360 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
362 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
365 if (!strcmp(dbg,"debug"))
367 if (!strcmp(dbg,"verbose"))
369 if (!strcmp(dbg,"default"))
371 if (!strcmp(dbg,"sparse"))
373 if (!strcmp(dbg,"none"))
376 log(DEFAULT,"Reading message of the day...");
377 readfile(RULES,rules);
378 log(DEFAULT,"Reading connect classes...");
380 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
383 ConfValue("connect","allow",i,Value,&config_f);
384 ConfValue("connect","timeout",i,timeout,&config_f);
385 ConfValue("connect","flood",i,flood,&config_f);
386 ConfValue("connect","pingfreq",i,pfreq,&config_f);
387 ConfValue("connect","threshold",i,thold,&config_f);
388 ConfValue("connect","sendq",i,sqmax,&config_f);
389 ConfValue("connect","recvq",i,rqmax,&config_f);
392 strlcpy(c.host,Value,MAXBUF);
394 strlcpy(Value,"",MAXBUF);
395 ConfValue("connect","password",i,Value,&config_f);
396 strlcpy(c.pass,Value,MAXBUF);
397 c.registration_timeout = 90; // default is 2 minutes
399 c.flood = atoi(flood);
401 c.sendqmax = 262144; // 256k
402 c.recvqmax = 4096; // 4k
405 c.threshold = atoi(thold);
409 c.sendqmax = atoi(sqmax);
413 c.recvqmax = atoi(rqmax);
417 c.registration_timeout = atoi(timeout);
421 c.pingtime = atoi(pfreq);
423 Classes.push_back(c);
424 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%lu flood=%lu",c.host,c.pass,(unsigned long)c.registration_timeout,(unsigned long)c.flood);
428 ConfValue("connect","deny",i,Value,&config_f);
429 strlcpy(c.host,Value,MAXBUF);
431 Classes.push_back(c);
432 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
436 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
437 read_xline_defaults();
438 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
442 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
444 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
445 ConfValue("link","name",i,Link_ServerName,&config_f);
446 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
447 if (strcmp(Link_AConn,""))
449 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
454 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
457 log(DEFAULT,"Adding and removing modules due to rehash...");
459 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
461 // store the old module names
462 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
464 old_module_names.push_back(*t);
467 // get the new module names
468 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
470 ConfValue("module","name",count2,Value,&config_f);
471 new_module_names.push_back(Value);
474 // now create a list of new modules that are due to be loaded
475 // and a seperate list of modules which are due to be unloaded
476 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
479 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
485 added_modules.push_back(*_new);
487 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
490 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
496 removed_modules.push_back(*oldm);
498 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
500 int rem = 0, add = 0;
501 if (!removed_modules.empty())
502 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
504 if (UnloadModule(removing->c_str()))
506 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
507 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
512 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
515 if (!added_modules.empty())
516 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
518 if (LoadModule(adding->c_str()))
520 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
521 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
526 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
529 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
534 /* add a channel to a user, creating the record for it if needed and linking
535 * it to the user record */
537 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
539 if ((!user) || (!cn))
541 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
549 strncpy(cname,cn,MAXBUF);
551 // we MUST declare this wherever we use FOREACH_RESULT
554 if (strlen(cname) > CHANMAX)
556 cname[CHANMAX] = '\0';
559 log(DEBUG,"add_channel: %s %s",user->nick,cname);
561 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
563 return NULL; // already on the channel!
567 if (!FindChan(cname))
570 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
571 if (MOD_RESULT == 1) {
575 /* create a new one */
576 log(DEBUG,"add_channel: creating: %s",cname);
578 chanlist[cname] = new chanrec();
580 strlcpy(chanlist[cname]->name, cname,CHANMAX);
581 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
582 chanlist[cname]->created = TIME;
583 strcpy(chanlist[cname]->topic, "");
584 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
585 chanlist[cname]->topicset = 0;
586 Ptr = chanlist[cname];
587 log(DEBUG,"add_channel: created: %s",cname);
588 /* set created to 2 to indicate user
589 * is the first in the channel
590 * and should be given ops */
596 /* channel exists, just fish out a pointer to its struct */
597 Ptr = FindChan(cname);
600 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
602 // the override flag allows us to bypass channel modes
603 // and bans (used by servers)
604 if ((!override) || (!strcasecmp(user->server,ServerName)))
606 log(DEBUG,"Not overriding...");
608 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
609 if (MOD_RESULT == 1) {
612 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
616 log(DEBUG,"add_channel: checking key, invite, etc");
618 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
623 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
626 log(DEBUG,"add_channel: no key given in JOIN");
627 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
632 if (strcasecmp(key,Ptr->key))
634 log(DEBUG,"add_channel: bad key given in JOIN");
635 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
640 log(DEBUG,"add_channel: no key");
643 FOREACH_RESULT(OnCheckInvite(user, Ptr));
646 if (Ptr->binarymodes & CM_INVITEONLY)
648 log(DEBUG,"add_channel: channel is +i");
649 if (user->IsInvited(Ptr->name))
651 /* user was invited to channel */
652 /* there may be an optional channel NOTICE here */
656 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
660 log(DEBUG,"add_channel: channel is not +i");
663 FOREACH_RESULT(OnCheckLimit(user, Ptr));
668 if (usercount(Ptr) >= Ptr->limit)
670 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
675 log(DEBUG,"add_channel: about to walk banlist");
677 FOREACH_RESULT(OnCheckBan(user, Ptr));
680 /* check user against the channel banlist */
683 if (Ptr->bans.size())
685 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
687 if (match(user->GetFullHost(),i->data))
689 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
695 log(DEBUG,"add_channel: bans checked");
703 user->RemoveInvite(Ptr->name);
706 log(DEBUG,"add_channel: invites removed");
711 log(DEBUG,"Overridden checks");
719 log(DEBUG,"Passed channel checks");
721 for (int index =0; index != MAXCHANS; index++)
723 log(DEBUG,"Check location %d",index);
724 if (user->chans[index].channel == NULL)
726 log(DEBUG,"Adding into their channel list at location %d",index);
730 /* first user in is given ops */
731 user->chans[index].uc_modes = UCMODE_OP;
735 user->chans[index].uc_modes = 0;
737 user->chans[index].channel = Ptr;
738 Ptr->AddUser((char*)user);
739 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
741 log(DEBUG,"Sent JOIN to client");
745 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
746 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
749 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
750 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
751 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
752 FOREACH_MOD OnUserJoin(user,Ptr);
756 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
757 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
761 /* remove a channel from a users record, and remove the record from memory
762 * if the channel has become empty */
764 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
766 if ((!user) || (!cname))
768 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
774 if ((!cname) || (!user))
779 Ptr = FindChan(cname);
786 FOREACH_MOD OnUserPart(user,Ptr);
787 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
789 for (int i =0; i != MAXCHANS; i++)
791 /* zap it from the channel list of the user */
792 if (user->chans[i].channel == Ptr)
796 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
800 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
802 user->chans[i].uc_modes = 0;
803 user->chans[i].channel = NULL;
804 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
809 Ptr->DelUser((char*)user);
811 /* if there are no users left on the channel */
814 chan_hash::iterator iter = chanlist.find(Ptr->name);
816 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
818 /* kill the record */
819 if (iter != chanlist.end())
821 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
823 chanlist.erase(iter);
831 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
833 if ((!src) || (!user) || (!Ptr) || (!reason))
835 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
839 if ((!Ptr) || (!user) || (!src))
844 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
846 if (!has_channel(user,Ptr))
848 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
853 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
854 if (MOD_RESULT == ACR_DENY)
857 if (MOD_RESULT == ACR_DEFAULT)
859 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
861 if (cstatus(src,Ptr) == STATUS_HOP)
863 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
867 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
875 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
879 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
881 for (int i =0; i != MAXCHANS; i++)
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))
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);
895 Ptr->DelUser((char*)user);
897 /* if there are no users left on the channel */
900 chan_hash::iterator iter = chanlist.find(Ptr->name);
902 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
904 /* kill the record */
905 if (iter != chanlist.end())
907 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
909 chanlist.erase(iter);
917 /* This function pokes and hacks at a parameter list like the following:
919 * PART #winbot,#darkgalaxy :m00!
921 * to turn it into a series of individual calls like this:
924 * PART #darkgalaxy :m00!
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) */
935 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
940 char blog[32][MAXBUF];
941 char blog2[32][MAXBUF];
942 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
946 for (int i = 0; i <32; i++)
949 for (int i = 0; i <32; i++)
953 for (int i = 0; i <10; i++)
962 if (pcnt > 1) /* we have a key to copy */
964 strlcpy(keystr,parameters[1],MAXBUF);
968 if (!parameters[start])
972 if (!strchr(parameters[start],','))
977 for (int i = start; i <= end; i++)
981 strlcat(plist,parameters[i],MAXBUF);
989 for (int i = 0; i < t; i++)
994 strlcpy(blog[j++],param,MAXBUF);
998 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1003 strlcpy(blog[j++],param,MAXBUF);
1006 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1011 if ((joins) && (keystr))
1013 if (strchr(keystr,','))
1017 t2 = strlen(keystr);
1018 for (int i = 0; i < t2; i++)
1020 if (keystr[i] == ',')
1023 strlcpy(blog2[j++],param,MAXBUF);
1027 strlcpy(blog2[j++],param,MAXBUF);
1032 for (j = 0; j < total; j++)
1038 for (q = end; q < pcnt-1; q++)
1040 if (parameters[q+1])
1042 pars[q-end+1] = parameters[q+1];
1045 if ((joins) && (parameters[1]))
1056 /* repeatedly call the function with the hacked parameter list */
1057 if ((joins) && (pcnt > 1))
1061 // pars[1] already set up and containing key from blog2[j]
1066 pars[1] = parameters[1];
1072 fn(pars,pcnt-(end-start),u);
1081 void kill_link(userrec *user,const char* r)
1083 user_hash::iterator iter = clientlist.find(user->nick);
1085 char reason[MAXBUF];
1087 strncpy(reason,r,MAXBUF);
1089 if (strlen(reason)>MAXQUIT)
1091 reason[MAXQUIT-1] = '\0';
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);
1098 if (user->registered == 7) {
1099 FOREACH_MOD OnUserQuit(user);
1100 WriteCommonExcept(user,"QUIT :%s",reason);
1103 user->FlushWriteBuf();
1105 FOREACH_MOD OnUserDisconnect(user);
1109 FOREACH_MOD OnRawSocketClose(user->fd);
1111 user->CloseSocket();
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);
1124 if (iter != clientlist.end())
1126 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1128 fd_ref_table[user->fd] = NULL;
1129 clientlist.erase(iter);
1134 void kill_link_silent(userrec *user,const char* r)
1136 user_hash::iterator iter = clientlist.find(user->nick);
1138 char reason[MAXBUF];
1140 strncpy(reason,r,MAXBUF);
1142 if (strlen(reason)>MAXQUIT)
1144 reason[MAXQUIT-1] = '\0';
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);
1151 user->FlushWriteBuf();
1153 if (user->registered == 7) {
1154 FOREACH_MOD OnUserQuit(user);
1155 WriteCommonExcept(user,"QUIT :%s",reason);
1158 FOREACH_MOD OnUserDisconnect(user);
1162 FOREACH_MOD OnRawSocketClose(user->fd);
1164 user->CloseSocket();
1167 if (user->registered == 7) {
1168 purge_empty_chans(user);
1171 if (iter != clientlist.end())
1173 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1175 fd_ref_table[user->fd] = NULL;
1176 clientlist.erase(iter);
1182 int main(int argc, char** argv)
1186 log(DEBUG,"*** InspIRCd starting up!");
1187 if (!FileExists(CONFIG_FILE))
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");
1195 for (int i = 1; i < argc; i++)
1197 if (!strcmp(argv[i],"-nofork")) {
1200 if (!strcmp(argv[i],"-wait")) {
1203 if (!strcmp(argv[i],"-nolimit")) {
1208 strlcpy(MyExecutable,argv[0],MAXBUF);
1210 // initialize the lowercase mapping table
1211 for (unsigned int cn = 0; cn < 256; cn++)
1213 // lowercase the uppercase chars
1214 for (unsigned int cn = 65; cn < 91; cn++)
1215 lowermap[cn] = tolower(cn);
1216 // now replace the specific chars for scandanavian comparison
1217 lowermap[(unsigned)'['] = '{';
1218 lowermap[(unsigned)']'] = '}';
1219 lowermap[(unsigned)'\\'] = '|';
1221 if (InspIRCd(argv,argc) == ERROR)
1223 log(DEFAULT,"main: daemon function bailed");
1224 printf("ERROR: could not initialise. Shutting down.\n");
1231 template<typename T> inline string ConvToStr(const T &in)
1234 if (!(tmp << in)) return string();
1238 /* re-allocates a nick in the user_hash after they change nicknames,
1239 * returns a pointer to the new user as it may have moved */
1241 userrec* ReHashNick(char* Old, char* New)
1243 //user_hash::iterator newnick;
1244 user_hash::iterator oldnick = clientlist.find(Old);
1246 log(DEBUG,"ReHashNick: %s %s",Old,New);
1248 if (!strcasecmp(Old,New))
1250 log(DEBUG,"old nick is new nick, skipping");
1251 return oldnick->second;
1254 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1256 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1258 userrec* olduser = oldnick->second;
1259 clientlist[New] = olduser;
1260 clientlist.erase(oldnick);
1262 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1264 return clientlist[New];
1267 /* adds or updates an entry in the whowas list */
1268 void AddWhoWas(userrec* u)
1270 whowas_hash::iterator iter = whowas.find(u->nick);
1271 WhoWasUser *a = new WhoWasUser();
1272 strlcpy(a->nick,u->nick,NICKMAX);
1273 strlcpy(a->ident,u->ident,IDENTMAX);
1274 strlcpy(a->dhost,u->dhost,160);
1275 strlcpy(a->host,u->host,160);
1276 strlcpy(a->fullname,u->fullname,MAXGECOS);
1277 strlcpy(a->server,u->server,256);
1278 a->signon = u->signon;
1280 /* MAX_WHOWAS: max number of /WHOWAS items
1281 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1282 * can be replaced by a newer one
1285 if (iter == whowas.end())
1287 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1289 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1291 // 3600 seconds in an hour ;)
1292 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1294 // delete the old one
1295 if (i->second) delete i->second;
1296 // replace with new one
1298 log(DEBUG,"added WHOWAS entry, purged an old record");
1302 // no space left and user doesnt exist. Don't leave ram in use!
1303 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1308 log(DEBUG,"added fresh WHOWAS entry");
1309 whowas[a->nick] = a;
1314 log(DEBUG,"updated WHOWAS entry");
1315 if (iter->second) delete iter->second;
1321 /* add a client connection to the sockets list */
1322 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1326 user_hash::iterator iter;
1328 tempnick = ConvToStr(socket) + "-unknown";
1329 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1331 iter = clientlist.find(tempnick);
1334 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1335 // using one as a registered connection. As theyre per fd, we can also safely assume
1336 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1337 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1338 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1339 // issue in earlier alphas/betas
1340 if (iter != clientlist.end())
1342 userrec* goner = iter->second;
1344 clientlist.erase(iter);
1348 * It is OK to access the value here this way since we know
1349 * it exists, we just created it above.
1351 * At NO other time should you access a value in a map or a
1352 * hash_map this way.
1354 clientlist[tempnick] = new userrec();
1356 NonBlocking(socket);
1357 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1359 clientlist[tempnick]->fd = socket;
1360 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1361 strlcpy(clientlist[tempnick]->host, host,160);
1362 strlcpy(clientlist[tempnick]->dhost, host,160);
1363 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1364 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1365 clientlist[tempnick]->registered = 0;
1366 clientlist[tempnick]->signon = TIME+dns_timeout;
1367 clientlist[tempnick]->lastping = 1;
1368 clientlist[tempnick]->port = port;
1369 strlcpy(clientlist[tempnick]->ip,ip,16);
1371 // set the registration timeout for this user
1372 unsigned long class_regtimeout = 90;
1373 int class_flood = 0;
1374 long class_threshold = 5;
1375 long class_sqmax = 262144; // 256kb
1376 long class_rqmax = 4096; // 4k
1378 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1380 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1382 class_regtimeout = (unsigned long)i->registration_timeout;
1383 class_flood = i->flood;
1384 clientlist[tempnick]->pingmax = i->pingtime;
1385 class_threshold = i->threshold;
1386 class_sqmax = i->sendqmax;
1387 class_rqmax = i->recvqmax;
1392 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1393 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1394 clientlist[tempnick]->flood = class_flood;
1395 clientlist[tempnick]->threshold = class_threshold;
1396 clientlist[tempnick]->sendqmax = class_sqmax;
1397 clientlist[tempnick]->recvqmax = class_rqmax;
1399 for (int i = 0; i < MAXCHANS; i++)
1401 clientlist[tempnick]->chans[i].channel = NULL;
1402 clientlist[tempnick]->chans[i].uc_modes = 0;
1405 if (clientlist.size() > SoftLimit)
1407 kill_link(clientlist[tempnick],"No more connections allowed");
1411 if (clientlist.size() >= MAXCLIENTS)
1413 kill_link(clientlist[tempnick],"No more connections allowed");
1417 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1418 // its a pretty big but for the moment valid assumption:
1419 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1420 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1421 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1422 // which for the time being is a physical impossibility (even the largest networks dont have more
1423 // than about 10,000 users on ONE server!)
1424 if ((unsigned)socket > 65534)
1426 kill_link(clientlist[tempnick],"Server is full");
1431 char* e = matches_exception(ip);
1434 char* r = matches_zline(ip);
1437 char reason[MAXBUF];
1438 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1439 kill_link(clientlist[tempnick],reason);
1443 fd_ref_table[socket] = clientlist[tempnick];
1447 /* shows the message of the day, and any other on-logon stuff */
1448 void FullConnectUser(userrec* user)
1451 user->idle_lastmsg = TIME;
1452 log(DEBUG,"ConnectUser: %s",user->nick);
1454 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1456 kill_link(user,"Invalid password");
1461 kill_link(user,"Unauthorised connection");
1465 char match_against[MAXBUF];
1466 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1467 char* e = matches_exception(match_against);
1470 char* r = matches_gline(match_against);
1473 char reason[MAXBUF];
1474 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1475 kill_link_silent(user,reason);
1478 r = matches_kline(user->host);
1481 char reason[MAXBUF];
1482 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1483 kill_link_silent(user,reason);
1488 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1489 user->registered = 7;
1491 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1492 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1493 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1494 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1495 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1496 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1497 std::stringstream v;
1498 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1499 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1500 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1502 std::string data005 = v.str();
1503 FOREACH_MOD On005Numeric(data005);
1504 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1505 // so i'd better split it :)
1506 std::stringstream out(data005);
1507 std::string token = "";
1508 std::string line5 = "";
1509 int token_counter = 0;
1513 line5 = line5 + token + " ";
1515 if ((token_counter >= 13) || (out.eof() == true))
1517 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1524 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1525 FOREACH_MOD OnUserConnect(user);
1526 FOREACH_MOD OnGlobalConnect(user);
1527 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1531 /* shows the message of the day, and any other on-logon stuff */
1532 void ConnectUser(userrec *user)
1534 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1535 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1537 FullConnectUser(user);
1541 std::string GetVersionString()
1543 char Revision[] = "$Revision$";
1544 char versiondata[MAXBUF];
1545 char *s1 = Revision;
1547 char *v2 = strtok_r(s1," ",&savept);
1549 v2 = strtok_r(s1," ",&savept);
1551 char socketengine[] = engine_name;
1552 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1556 void handle_version(char **parameters, int pcnt, userrec *user)
1558 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1562 // calls a handler function for a command
1564 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1566 for (unsigned int i = 0; i < cmdlist.size(); i++)
1568 if (!strcasecmp(cmdlist[i].command,commandname))
1570 if (cmdlist[i].handler_function)
1572 if (pcnt>=cmdlist[i].min_params)
1574 if (strchr(user->modes,cmdlist[i].flags_needed))
1576 cmdlist[i].handler_function(parameters,pcnt,user);
1585 void force_nickchange(userrec* user,const char* newnick)
1592 FOREACH_RESULT(OnUserPreNick(user,newnick));
1595 kill_link(user,"Nickname collision");
1598 if (matches_qline(newnick))
1601 kill_link(user,"Nickname collision");
1609 strncpy(nick,newnick,MAXBUF);
1611 if (user->registered == 7)
1615 handle_nick(pars,1,user);
1621 int process_parameters(char **command_p,char *parameters)
1624 int q = strlen(parameters);
1627 /* no parameters, command_p invalid! */
1630 if (parameters[0] == ':')
1632 command_p[0] = parameters+1;
1637 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1639 /* only one parameter */
1640 command_p[0] = parameters;
1641 if (parameters[0] == ':')
1643 if (strchr(parameters,' ') != NULL)
1651 command_p[j++] = parameters;
1652 for (int i = 0; i <= q; i++)
1654 if (parameters[i] == ' ')
1656 command_p[j++] = parameters+i+1;
1657 parameters[i] = '\0';
1658 if (command_p[j-1][0] == ':')
1660 *command_p[j-1]++; /* remove dodgy ":" */
1662 /* parameter like this marks end of the sequence */
1666 return j; /* returns total number of items in the list */
1669 void process_command(userrec *user, char* cmd)
1673 char *command_p[127];
1674 char p[MAXBUF], temp[MAXBUF];
1675 int j, items, cmd_found;
1677 for (int i = 0; i < 127; i++)
1678 command_p[i] = NULL;
1693 int total_params = 0;
1696 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1698 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1701 // found a 'trailing', we dont count them after this.
1709 // another phidjit bug...
1710 if (total_params > 126)
1712 *(strchr(cmd,' ')) = '\0';
1713 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1717 strlcpy(temp,cmd,MAXBUF);
1719 std::string tmp = cmd;
1720 for (int i = 0; i <= MODCOUNT; i++)
1722 std::string oldtmp = tmp;
1723 modules[i]->OnServerRaw(tmp,true,user);
1726 log(DEBUG,"A Module changed the input string!");
1727 log(DEBUG,"New string: %s",tmp.c_str());
1728 log(DEBUG,"Old string: %s",oldtmp.c_str());
1732 strlcpy(cmd,tmp.c_str(),MAXBUF);
1733 strlcpy(temp,cmd,MAXBUF);
1735 if (!strchr(cmd,' '))
1737 /* no parameters, lets skip the formalities and not chop up
1739 log(DEBUG,"About to preprocess command with no params");
1741 command_p[0] = NULL;
1743 for (unsigned int i = 0; i <= strlen(cmd); i++)
1745 cmd[i] = toupper(cmd[i]);
1753 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1754 for (unsigned int i = 0; i < strlen(temp); i++)
1756 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1762 /* split the full string into a command plus parameters */
1766 if (strchr(cmd,' '))
1768 for (unsigned int i = 0; i <= strlen(cmd); i++)
1770 /* capitalise the command ONLY, leave params intact */
1771 cmd[i] = toupper(cmd[i]);
1772 /* are we nearly there yet?! :P */
1776 parameters = cmd+i+1;
1784 for (unsigned int i = 0; i <= strlen(cmd); i++)
1786 cmd[i] = toupper(cmd[i]);
1793 if (strlen(command)>MAXCOMMAND)
1795 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1799 for (unsigned int x = 0; x < strlen(command); x++)
1801 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1803 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1805 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1808 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1815 for (unsigned int i = 0; i != cmdlist.size(); i++)
1817 if (cmdlist[i].command[0])
1819 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1825 items = process_parameters(command_p,parameters);
1830 command_p[0] = NULL;
1836 command_p[0] = NULL;
1841 /* activity resets the ping pending timer */
1842 user->nping = TIME + user->pingmax;
1843 if ((items) < cmdlist[i].min_params)
1845 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1846 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1849 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1851 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1852 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1856 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1858 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1859 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1863 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1865 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1867 if ((!isnick(user->nick)) || (user->registered != 7))
1869 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1870 WriteServ(user->fd,"451 %s :You have not registered",command);
1874 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1876 std::stringstream dcmds(DisabledCommands);
1877 while (!dcmds.eof())
1879 std::string thiscmd;
1881 if (!strcasecmp(thiscmd.c_str(),command))
1883 // command is disabled!
1884 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1889 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1891 if (cmdlist[i].handler_function)
1894 /* ikky /stats counters */
1897 cmdlist[i].use_count++;
1898 cmdlist[i].total_bytes+=strlen(temp);
1902 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1903 if (MOD_RESULT == 1) {
1907 /* WARNING: nothing may come after the
1908 * command handler call, as the handler
1909 * may free the user structure! */
1911 cmdlist[i].handler_function(command_p,items,user);
1917 WriteServ(user->fd,"451 %s :You have not registered",command);
1925 if ((!cmd_found) && (user))
1928 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1932 bool removecommands(const char* source)
1934 bool go_again = true;
1938 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1940 if (!strcmp(i->source,source))
1942 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1953 void process_buffer(const char* cmdbuf,userrec *user)
1957 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1963 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1970 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1972 strlcpy(cmd,cmdbuf,MAXBUF);
1977 int sl = strlen(cmd)-1;
1978 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1983 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1988 while (cmd[sl] == ' ') // strip trailing spaces
1998 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2000 if ((user) && (cmd))
2002 process_command(user,cmd);
2006 char MODERR[MAXBUF];
2013 void erase_factory(int j)
2016 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2021 factory.push_back(NULL);
2028 void erase_module(int j)
2031 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2037 modules.push_back(NULL);
2043 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2047 module_names.erase(v);
2055 bool UnloadModule(const char* filename)
2057 std::string filename_str = filename;
2058 for (unsigned int j = 0; j != module_names.size(); j++)
2060 if (module_names[j] == filename_str)
2062 if (modules[j]->GetVersion().Flags & VF_STATIC)
2064 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2065 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2068 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2070 log(DEBUG,"Deleting module...");
2072 log(DEBUG,"Erasing module entry...");
2074 log(DEBUG,"Removing dependent commands...");
2075 removecommands(filename);
2076 log(DEFAULT,"Module %s unloaded",filename);
2081 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2082 snprintf(MODERR,MAXBUF,"Module not loaded");
2086 bool LoadModule(const char* filename)
2088 char modfile[MAXBUF];
2090 snprintf(modfile,MAXBUF,"%s",filename);
2092 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2094 std::string filename_str = filename;
2096 if (!DirValid(modfile))
2098 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2099 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2103 log(DEBUG,"Loading module: %s",modfile);
2105 if (FileExists(modfile))
2108 for (unsigned int j = 0; j < module_names.size(); j++)
2110 if (module_names[j] == filename_str)
2112 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2113 snprintf(MODERR,MAXBUF,"Module already loaded");
2117 ircd_module* a = new ircd_module(modfile);
2118 factory[MODCOUNT+1] = a;
2119 if (factory[MODCOUNT+1]->LastError())
2121 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2122 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2126 if (factory[MODCOUNT+1]->factory)
2128 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2129 modules[MODCOUNT+1] = m;
2130 /* save the module and the module's classfactory, if
2131 * this isnt done, random crashes can occur :/ */
2132 module_names.push_back(filename);
2136 log(DEFAULT,"Unable to load %s",modfile);
2137 snprintf(MODERR,MAXBUF,"Factory function failed!");
2144 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2145 snprintf(MODERR,MAXBUF,"Module file could not be found");
2150 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2155 int InspIRCd(char** argv, int argc)
2157 struct sockaddr_in client,server;
2158 char addrs[MAXBUF][255];
2159 int incomingSockfd, result = TRUE;
2163 int selectResult = 0, selectResult2 = 0;
2166 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2169 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2170 log_file = fopen(logpath.c_str(),"a+");
2173 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2178 printf("Logging to ircd.log...\n");
2180 printf("Logging to %s...\n",logpath.c_str());
2183 log(DEFAULT,"$Id$");
2186 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2188 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2190 SetupCommandTable();
2191 log(DEBUG,"InspIRCd: startup: default command table set up");
2193 ReadConfig(true,NULL);
2196 printf("WARNING: %s\n\n",DieValue);
2197 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2200 log(DEBUG,"InspIRCd: startup: read config");
2202 AddServerName(ServerName);
2204 int clientportcount = 0;
2206 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2208 ConfValue("bind","port",count,configToken,&config_f);
2209 ConfValue("bind","address",count,Addr,&config_f);
2210 ConfValue("bind","type",count,Type,&config_f);
2211 if (!strcmp(Type,"servers"))
2213 // modules handle this bind type now.
2217 ports[clientportcount] = atoi(configToken);
2218 strlcpy(addrs[clientportcount],Addr,256);
2221 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2223 portCount = clientportcount;
2225 log(DEBUG,"InspIRCd: startup: read %lu total client ports",(unsigned long)portCount);
2226 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2230 /* BugFix By Craig! :p */
2232 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2234 ConfValue("module","name",count,configToken,&config_f);
2235 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2236 if (!LoadModule(configToken))
2238 log(DEFAULT,"Exiting due to a module loader error.");
2239 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2243 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2245 startup_time = time(NULL);
2248 ConfValue("pid","file",0,PID,&config_f);
2249 // write once here, to try it out and make sure its ok
2252 /* setup select call */
2254 FD_ZERO(&selectFds);
2256 log(DEBUG,"InspIRCd: startup: zero selects");
2257 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2259 for (count = 0; count < portCount; count++)
2261 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2263 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2266 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2268 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2270 else /* well we at least bound to one socket so we'll continue */
2276 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2278 /* if we didn't bind to anything then abort */
2279 if (boundPortCount == 0)
2281 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2282 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2287 printf("\nInspIRCd is now running!\n");
2291 log(VERBOSE,"Not forking as -nofork was specified");
2295 if (DaemonSeed() == ERROR)
2297 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2298 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2308 length = sizeof (client);
2311 tvs.tv_usec = 10000L;
2314 tv.tv_usec = 10000L;
2317 tval.tv_usec = 10000L;
2319 int total_in_this_set = 0;
2320 int i = 0, v = 0, j = 0, cycle_iter = 0;
2321 bool expire_run = false;
2323 cycle_iter = i = j = 0; // stop the compiler whining - these may be marked unused in certain socket engine types
2325 /* main loop, this never returns */
2328 #ifdef _POSIX_PRIORITY_SCHEDULING
2334 // we only read time() once per iteration rather than tons of times!
2340 unsigned int numsockets = module_sockets.size();
2341 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2343 InspSocket* s = (InspSocket*)*a;
2344 if ((s) && (!s->Poll()))
2346 log(DEBUG,"Socket poll returned false, close and bail");
2348 module_sockets.erase(a);
2352 // we gained a socket, sarper
2353 if (module_sockets.size() != numsockets) break;
2356 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2357 // them in a list, then reap the list every second or so.
2358 if (((TIME % 5) == 0) && (!expire_run))
2361 FOREACH_MOD OnBackgroundTimer(TIME);
2365 if ((TIME % 5) == 1)
2368 // fix by brain - this must be below any manipulation of the hashmap by modules
2369 user_hash::iterator count2 = clientlist.begin();
2372 while (count2 != clientlist.end())
2378 total_in_this_set = 0;
2380 user_hash::iterator xcount = count2;
2381 user_hash::iterator endingiter = count2;
2383 if (count2 == clientlist.end()) break;
2385 userrec* curr = NULL;
2388 curr = count2->second;
2390 if ((long)curr == -1)
2393 if ((curr) && (curr->fd != 0))
2395 #ifdef _POSIX_PRIORITY_SCHEDULING
2398 // assemble up to 64 sockets into an fd_set
2399 // to implement a pooling mechanism.
2401 // This should be up to 64x faster than the
2402 // old implementation.
2404 while (total_in_this_set < 1024)
2406 if (count2 != clientlist.end())
2408 curr = count2->second;
2409 if ((long)curr == -1)
2411 int currfd = curr->fd;
2412 // we don't check the state of remote users.
2413 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2415 curr->FlushWriteBuf();
2416 if (curr->GetWriteError() != "")
2418 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2419 kill_link(curr,curr->GetWriteError().c_str());
2423 FD_SET (curr->fd, &sfd);
2425 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2426 // their connection class.
2427 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2429 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2430 kill_link(curr,"Registration timeout");
2433 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2435 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
2436 curr->dns_done = true;
2438 FullConnectUser(curr);
2439 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2442 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
2444 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2445 FullConnectUser(curr);
2446 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2449 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2451 if ((!curr->lastping) && (curr->registered == 7))
2453 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2454 kill_link(curr,"Ping timeout");
2457 Write(curr->fd,"PING :%s",ServerName);
2458 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2460 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2464 total_in_this_set++;
2468 endingiter = count2;
2469 count2 = xcount; // roll back to where we were
2471 // 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.
2472 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
2474 if (cycle_iter > 20) while (count2 != clientlist.end())
2477 if (count2 != clientlist.end())
2479 curr = count2->second;
2480 if ((long)curr == -1)
2482 int currfd = curr->fd;
2483 // we don't check the state of remote users.
2484 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2486 curr->FlushWriteBuf();
2487 if (curr->GetWriteError() != "")
2489 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2490 kill_link(curr,curr->GetWriteError().c_str());
2494 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2495 // their connection class.
2496 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2498 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2499 kill_link(curr,"Registration timeout");
2503 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2505 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
2506 curr->dns_done = true;
2508 FullConnectUser(curr);
2509 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2512 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2514 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2515 FullConnectUser(curr);
2516 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2519 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2521 if ((!curr->lastping) && (curr->registered == 7))
2523 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2524 kill_link(curr,"Ping timeout");
2527 Write(curr->fd,"PING :%s",ServerName);
2528 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2530 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2537 // increment the counter right to the end of the list, as kqueue processes everything in one go
2543 #ifdef _POSIX_PRIORITY_SCHEDULING
2549 log(DEBUG,"Data waiting on socket %d",cu->fd);
2552 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
2555 result = cu->ReadData(data, 65535);
2559 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
2562 log(DEBUG,"Read result: %d",result);
2565 statsRecv += result;
2566 // perform a check on the raw buffer as an array (not a string!) to remove
2567 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
2568 // hopefully this should stop even more people whining about "Unknown command: *"
2569 for (int checker = 0; checker < result; checker++)
2571 if ((data[checker] == 0) || (data[checker] == 7))
2572 data[checker] = ' ';
2575 data[result] = '\0';
2576 userrec* current = cu;
2577 int currfd = current->fd;
2579 // add the data to the users buffer
2581 if (!current->AddBuffer(data))
2583 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
2584 if (current->registered == 7)
2586 kill_link(current,"RecvQ exceeded");
2590 WriteOpers("*** Excess flood from %s",current->ip);
2591 log(DEFAULT,"Excess flood from: %s",current->ip);
2592 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2597 if (current->recvq.length() > (unsigned)NetBufferSize)
2599 if (current->registered == 7)
2601 kill_link(current,"RecvQ exceeded");
2605 WriteOpers("*** Excess flood from %s",current->ip);
2606 log(DEFAULT,"Excess flood from: %s",current->ip);
2607 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2612 // while there are complete lines to process...
2613 while (current->BufferIsReady())
2616 if (TIME > current->reset_due)
2618 current->reset_due = TIME + current->threshold;
2619 current->lines_in = 0;
2621 current->lines_in++;
2622 if (current->lines_in > current->flood)
2624 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2625 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2626 kill_link(current,"Excess flood");
2629 if ((floodlines > current->flood) && (current->flood != 0))
2631 if (current->registered == 7)
2633 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2634 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2635 kill_link(current,"Excess flood");
2639 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2644 char sanitized[MAXBUF];
2645 // use GetBuffer to copy single lines into the sanitized string
2646 std::string single_line = current->GetBuffer();
2647 current->bytes_in += single_line.length();
2649 if (single_line.length()>512)
2651 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2652 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2653 kill_link(current,"Excess flood");
2656 strlcpy(sanitized,single_line.c_str(),MAXBUF);
2659 userrec* old_comp = fd_ref_table[currfd];
2660 // we're gonna re-scan to check if the nick is gone, after every
2661 // command - if it has, we're gonna bail
2662 process_buffer(sanitized,current);
2663 // look for the user's record in case it's changed... if theyve quit,
2664 // we cant do anything more with their buffer, so bail.
2665 // there used to be an ugly, slow loop here. Now we have a reference
2666 // table, life is much easier (and FASTER)
2667 userrec* new_comp = fd_ref_table[currfd];
2668 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
2676 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
2678 log(DEBUG,"killing: %s",cu->nick);
2679 kill_link(cu,strerror(errno));
2683 // result EAGAIN means nothing read
2684 if (result == EAGAIN)
2692 else if (result > 0)
2697 for (int q = 0; q < total_in_this_set; q++)
2703 #ifdef _POSIX_PRIORITY_SCHEDULING
2709 char target[MAXBUF], resolved[MAXBUF];
2710 length = sizeof (client);
2711 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2712 log(DEBUG,"Accepted socket %d",incomingSockfd);
2714 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2715 strlcpy (resolved, target, MAXBUF);
2717 if (incomingSockfd < 0)
2719 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
2720 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
2725 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
2727 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
2728 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2735 #ifdef _POSIX_PRIORITY_SCHEDULING
2741 close (incomingSockfd);