1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 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>
54 #include "connection.h"
66 #include "inspstring.h"
68 #include "helperfuncs.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 extern int MaxWhoResults;
97 char DisabledCommands[MAXBUF];
99 bool AllowHalfop = true;
100 bool AllowProtect = true;
101 bool AllowFounder = true;
103 extern std::vector<Module*> modules;
104 std::vector<std::string> module_names;
105 extern std::vector<ircd_module*> factory;
108 int openSockfd[MAXSOCKS];
110 bool unlimitcore = false;
112 time_t TIME = time(NULL), OLDTIME = time(NULL);
122 bool has_been_netsplit = false;
123 extern std::vector<std::string> include_stack;
125 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
126 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
127 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
128 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
129 typedef std::deque<command_t> command_table;
130 typedef std::map<std::string,time_t> autoconnects;
131 typedef std::vector<std::string> servernamelist;
133 // This table references users by file descriptor.
134 // its an array to make it VERY fast, as all lookups are referenced
135 // by an integer, meaning there is no need for a scan/search operation.
136 userrec* fd_ref_table[65536];
138 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
144 user_hash clientlist;
147 command_table cmdlist;
148 autoconnects autoconns;
154 servernamelist servernames;
156 struct linger linger = { 0 };
157 char MyExecutable[1024];
158 int boundPortCount = 0;
159 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
160 int defaultRoute = 0;
161 char ModPath[MAXBUF];
165 int has_channel(userrec *u, chanrec *c);
166 int usercount(chanrec *c);
167 int usercount_i(chanrec *c);
168 char* Passwd(userrec *user);
169 bool IsDenied(userrec *user);
170 void AddWhoWas(userrec* u);
172 std::vector<long> auth_cookies;
173 std::stringstream config_f(stringstream::in | stringstream::out);
175 std::vector<userrec*> all_opers;
179 void AddOper(userrec* user)
181 log(DEBUG,"Oper added to optimization list");
182 all_opers.push_back(user);
185 void AddServerName(std::string servername)
187 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
189 if (*a == servername)
192 servernames.push_back(servername);
195 const char* FindServerNamePtr(std::string servername)
197 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
199 if (*a == servername)
205 void DeleteOper(userrec* user)
207 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
211 log(DEBUG,"Oper removed from optimization list");
218 std::string GetRevision()
220 char Revision[] = "$Revision$";
223 char *v2 = strtok_r(s1," ",&savept);
225 v2 = strtok_r(s1," ",&savept);
227 return std::string(v2);
231 std::string getservername()
236 std::string getserverdesc()
241 std::string getnetworkname()
246 std::string getadminname()
251 std::string getadminemail()
256 std::string getadminnick()
261 void ReadConfig(bool bail, userrec* user)
263 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
264 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
266 std::stringstream errstr;
267 include_stack.clear();
269 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
272 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
275 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
283 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
284 while (!errstr.eof())
286 errstr.getline(dataline,1024);
287 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
292 WriteOpers("There were errors in the configuration file:",user->nick);
293 while (!errstr.eof())
295 errstr.getline(dataline,1024);
296 WriteOpers(dataline);
303 ConfValue("server","name",0,ServerName,&config_f);
304 ConfValue("server","description",0,ServerDesc,&config_f);
305 ConfValue("server","network",0,Network,&config_f);
306 ConfValue("admin","name",0,AdminName,&config_f);
307 ConfValue("admin","email",0,AdminEmail,&config_f);
308 ConfValue("admin","nick",0,AdminNick,&config_f);
309 ConfValue("files","motd",0,motd,&config_f);
310 ConfValue("files","rules",0,rules,&config_f);
311 ConfValue("power","diepass",0,diepass,&config_f);
312 ConfValue("power","pause",0,pauseval,&config_f);
313 ConfValue("power","restartpass",0,restartpass,&config_f);
314 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
315 ConfValue("die","value",0,DieValue,&config_f);
316 ConfValue("options","loglevel",0,dbg,&config_f);
317 ConfValue("options","netbuffersize",0,NB,&config_f);
318 ConfValue("options","maxwho",0,MW,&config_f);
319 ConfValue("options","allowhalfop",0,AH,&config_f);
320 ConfValue("options","allowprotect",0,AP,&config_f);
321 ConfValue("options","allowfounder",0,AF,&config_f);
322 ConfValue("dns","server",0,DNSServer,&config_f);
323 ConfValue("dns","timeout",0,DNT,&config_f);
324 ConfValue("options","moduledir",0,ModPath,&config_f);
325 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
326 ConfValue("options","somaxconn",0,MCON,&config_f);
328 MaxConn = atoi(MCON);
329 if (MaxConn > SOMAXCONN)
330 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
331 NetBufferSize = atoi(NB);
332 MaxWhoResults = atoi(MW);
333 dns_timeout = atoi(DNT);
339 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
341 strlcpy(ModPath,MOD_PATH,MAXBUF);
342 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
343 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
344 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
345 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
347 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
348 NetBufferSize = 10240;
350 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
352 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
355 if (!strcmp(dbg,"debug"))
357 if (!strcmp(dbg,"verbose"))
359 if (!strcmp(dbg,"default"))
361 if (!strcmp(dbg,"sparse"))
363 if (!strcmp(dbg,"none"))
366 log(DEFAULT,"Reading message of the day...");
367 readfile(RULES,rules);
368 log(DEFAULT,"Reading connect classes...");
370 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
373 ConfValue("connect","allow",i,Value,&config_f);
374 ConfValue("connect","timeout",i,timeout,&config_f);
375 ConfValue("connect","flood",i,flood,&config_f);
376 ConfValue("connect","pingfreq",i,pfreq,&config_f);
377 ConfValue("connect","threshold",i,thold,&config_f);
378 ConfValue("connect","sendq",i,sqmax,&config_f);
379 ConfValue("connect","recvq",i,rqmax,&config_f);
382 strlcpy(c.host,Value,MAXBUF);
384 strlcpy(Value,"",MAXBUF);
385 ConfValue("connect","password",i,Value,&config_f);
386 strlcpy(c.pass,Value,MAXBUF);
387 c.registration_timeout = 90; // default is 2 minutes
389 c.flood = atoi(flood);
391 c.sendqmax = 262144; // 256k
392 c.recvqmax = 4096; // 4k
395 c.threshold = atoi(thold);
399 c.sendqmax = atoi(sqmax);
403 c.recvqmax = atoi(rqmax);
407 c.registration_timeout = atoi(timeout);
411 c.pingtime = atoi(pfreq);
413 Classes.push_back(c);
414 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);
418 ConfValue("connect","deny",i,Value,&config_f);
419 strlcpy(c.host,Value,MAXBUF);
421 Classes.push_back(c);
422 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
426 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
427 read_xline_defaults();
428 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
432 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
434 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
435 ConfValue("link","name",i,Link_ServerName,&config_f);
436 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
437 if (strcmp(Link_AConn,""))
439 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
444 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
447 log(DEFAULT,"Adding and removing modules due to rehash...");
449 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
451 // store the old module names
452 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
454 old_module_names.push_back(*t);
457 // get the new module names
458 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
460 ConfValue("module","name",count2,Value,&config_f);
461 new_module_names.push_back(Value);
464 // now create a list of new modules that are due to be loaded
465 // and a seperate list of modules which are due to be unloaded
466 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
469 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
475 added_modules.push_back(*_new);
477 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
480 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
486 removed_modules.push_back(*oldm);
488 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
490 int rem = 0, add = 0;
491 if (!removed_modules.empty())
492 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
494 if (UnloadModule(removing->c_str()))
496 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
497 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
502 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
505 if (!added_modules.empty())
506 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
508 if (LoadModule(adding->c_str()))
510 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
511 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
516 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
519 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
524 /* add a channel to a user, creating the record for it if needed and linking
525 * it to the user record */
527 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
529 if ((!user) || (!cn))
531 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
539 strncpy(cname,cn,MAXBUF);
541 // we MUST declare this wherever we use FOREACH_RESULT
544 if (strlen(cname) > CHANMAX)
546 cname[CHANMAX] = '\0';
549 log(DEBUG,"add_channel: %s %s",user->nick,cname);
551 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
553 return NULL; // already on the channel!
557 if (!FindChan(cname))
560 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
561 if (MOD_RESULT == 1) {
565 /* create a new one */
566 log(DEBUG,"add_channel: creating: %s",cname);
568 chanlist[cname] = new chanrec();
570 strlcpy(chanlist[cname]->name, cname,CHANMAX);
571 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
572 chanlist[cname]->created = TIME;
573 strcpy(chanlist[cname]->topic, "");
574 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
575 chanlist[cname]->topicset = 0;
576 Ptr = chanlist[cname];
577 log(DEBUG,"add_channel: created: %s",cname);
578 /* set created to 2 to indicate user
579 * is the first in the channel
580 * and should be given ops */
586 /* channel exists, just fish out a pointer to its struct */
587 Ptr = FindChan(cname);
590 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
592 // the override flag allows us to bypass channel modes
593 // and bans (used by servers)
594 if ((!override) || (!strcasecmp(user->server,ServerName)))
596 log(DEBUG,"Not overriding...");
598 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
599 if (MOD_RESULT == 1) {
602 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
606 log(DEBUG,"add_channel: checking key, invite, etc");
608 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
613 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
616 log(DEBUG,"add_channel: no key given in JOIN");
617 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
622 if (strcasecmp(key,Ptr->key))
624 log(DEBUG,"add_channel: bad key given in JOIN");
625 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
630 log(DEBUG,"add_channel: no key");
633 FOREACH_RESULT(OnCheckInvite(user, Ptr));
636 if (Ptr->binarymodes & CM_INVITEONLY)
638 log(DEBUG,"add_channel: channel is +i");
639 if (user->IsInvited(Ptr->name))
641 /* user was invited to channel */
642 /* there may be an optional channel NOTICE here */
646 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
650 log(DEBUG,"add_channel: channel is not +i");
653 FOREACH_RESULT(OnCheckLimit(user, Ptr));
658 if (usercount(Ptr) >= Ptr->limit)
660 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
665 log(DEBUG,"add_channel: about to walk banlist");
667 FOREACH_RESULT(OnCheckBan(user, Ptr));
670 /* check user against the channel banlist */
673 if (Ptr->bans.size())
675 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
677 if (match(user->GetFullHost(),i->data))
679 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
685 log(DEBUG,"add_channel: bans checked");
693 user->RemoveInvite(Ptr->name);
696 log(DEBUG,"add_channel: invites removed");
701 log(DEBUG,"Overridden checks");
709 log(DEBUG,"Passed channel checks");
711 for (int index =0; index != MAXCHANS; index++)
713 log(DEBUG,"Check location %d",index);
714 if (user->chans[index].channel == NULL)
716 log(DEBUG,"Adding into their channel list at location %d",index);
720 /* first user in is given ops */
721 user->chans[index].uc_modes = UCMODE_OP;
725 user->chans[index].uc_modes = 0;
727 user->chans[index].channel = Ptr;
728 Ptr->AddUser((char*)user);
729 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
731 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
733 // use the stamdard J token with no privilages.
737 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
741 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
743 NetSendToAll(buffer);
746 log(DEBUG,"Sent JOIN to client");
750 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
751 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
754 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
755 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
756 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
757 FOREACH_MOD OnUserJoin(user,Ptr);
761 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
762 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
766 /* remove a channel from a users record, and remove the record from memory
767 * if the channel has become empty */
769 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
771 if ((!user) || (!cname))
773 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
779 if ((!cname) || (!user))
784 Ptr = FindChan(cname);
791 FOREACH_MOD OnUserPart(user,Ptr);
792 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
794 for (int i =0; i != MAXCHANS; i++)
796 /* zap it from the channel list of the user */
797 if (user->chans[i].channel == Ptr)
801 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
806 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
807 NetSendToAll(buffer);
817 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
818 NetSendToAll(buffer);
821 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
823 user->chans[i].uc_modes = 0;
824 user->chans[i].channel = NULL;
825 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
830 Ptr->DelUser((char*)user);
832 /* if there are no users left on the channel */
835 chan_hash::iterator iter = chanlist.find(Ptr->name);
837 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
839 /* kill the record */
840 if (iter != chanlist.end())
842 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
844 chanlist.erase(iter);
852 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
854 if ((!src) || (!user) || (!Ptr) || (!reason))
856 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
860 if ((!Ptr) || (!user) || (!src))
865 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
867 if (!has_channel(user,Ptr))
869 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
874 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
875 if (MOD_RESULT == ACR_DENY)
878 if (MOD_RESULT == ACR_DEFAULT)
880 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
882 if (cstatus(src,Ptr) == STATUS_HOP)
884 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
888 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
896 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
900 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
902 for (int i =0; i != MAXCHANS; i++)
904 /* zap it from the channel list of the user */
905 if (user->chans[i].channel)
906 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
908 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
909 user->chans[i].uc_modes = 0;
910 user->chans[i].channel = NULL;
911 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
916 Ptr->DelUser((char*)user);
918 /* if there are no users left on the channel */
921 chan_hash::iterator iter = chanlist.find(Ptr->name);
923 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
925 /* kill the record */
926 if (iter != chanlist.end())
928 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
930 chanlist.erase(iter);
938 /* This function pokes and hacks at a parameter list like the following:
940 * PART #winbot,#darkgalaxy :m00!
942 * to turn it into a series of individual calls like this:
945 * PART #darkgalaxy :m00!
947 * The seperate calls are sent to a callback function provided by the caller
948 * (the caller will usually call itself recursively). The callback function
949 * must be a command handler. Calling this function on a line with no list causes
950 * no action to be taken. You must provide a starting and ending parameter number
951 * where the range of the list can be found, useful if you have a terminating
952 * parameter as above which is actually not part of the list, or parameters
953 * before the actual list as well. This code is used by many functions which
954 * can function as "one to list" (see the RFC) */
956 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
961 char blog[32][MAXBUF];
962 char blog2[32][MAXBUF];
963 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
967 for (int i = 0; i <32; i++)
970 for (int i = 0; i <32; i++)
974 for (int i = 0; i <10; i++)
983 if (pcnt > 1) /* we have a key to copy */
985 strlcpy(keystr,parameters[1],MAXBUF);
989 if (!parameters[start])
993 if (!strchr(parameters[start],','))
998 for (int i = start; i <= end; i++)
1002 strlcat(plist,parameters[i],MAXBUF);
1010 for (int i = 0; i < t; i++)
1012 if (plist[i] == ',')
1015 strlcpy(blog[j++],param,MAXBUF);
1019 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1024 strlcpy(blog[j++],param,MAXBUF);
1027 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1032 if ((joins) && (keystr))
1034 if (strchr(keystr,','))
1038 t2 = strlen(keystr);
1039 for (int i = 0; i < t2; i++)
1041 if (keystr[i] == ',')
1044 strlcpy(blog2[j++],param,MAXBUF);
1048 strlcpy(blog2[j++],param,MAXBUF);
1053 for (j = 0; j < total; j++)
1059 for (q = end; q < pcnt-1; q++)
1061 if (parameters[q+1])
1063 pars[q-end+1] = parameters[q+1];
1066 if ((joins) && (parameters[1]))
1077 /* repeatedly call the function with the hacked parameter list */
1078 if ((joins) && (pcnt > 1))
1082 // pars[1] already set up and containing key from blog2[j]
1087 pars[1] = parameters[1];
1093 fn(pars,pcnt-(end-start),u);
1102 void kill_link(userrec *user,const char* r)
1104 user_hash::iterator iter = clientlist.find(user->nick);
1106 char reason[MAXBUF];
1108 strncpy(reason,r,MAXBUF);
1110 if (strlen(reason)>MAXQUIT)
1112 reason[MAXQUIT-1] = '\0';
1115 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1116 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1117 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1119 if (user->registered == 7) {
1120 FOREACH_MOD OnUserQuit(user);
1121 WriteCommonExcept(user,"QUIT :%s",reason);
1123 // Q token must go to ALL servers!!!
1124 char buffer[MAXBUF];
1125 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1126 NetSendToAll(buffer);
1129 user->FlushWriteBuf();
1131 FOREACH_MOD OnUserDisconnect(user);
1135 FOREACH_MOD OnRawSocketClose(user->fd);
1138 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1139 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1142 log(DEBUG,"kqueue: Failed to remove user from queue!");
1146 struct epoll_event ev;
1147 ev.events = EPOLLIN | EPOLLET;
1148 ev.data.fd = user->fd;
1149 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1152 log(DEBUG,"epoll: List deletion failure!");
1155 user->CloseSocket();
1158 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1159 // if they were an oper with +s.
1160 if (user->registered == 7) {
1161 purge_empty_chans(user);
1162 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1163 if (!strcmp(user->server,ServerName))
1164 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1168 if (iter != clientlist.end())
1170 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1172 fd_ref_table[user->fd] = NULL;
1173 clientlist.erase(iter);
1178 void kill_link_silent(userrec *user,const char* r)
1180 user_hash::iterator iter = clientlist.find(user->nick);
1182 char reason[MAXBUF];
1184 strncpy(reason,r,MAXBUF);
1186 if (strlen(reason)>MAXQUIT)
1188 reason[MAXQUIT-1] = '\0';
1191 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1192 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1193 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1195 user->FlushWriteBuf();
1197 if (user->registered == 7) {
1198 FOREACH_MOD OnUserQuit(user);
1199 WriteCommonExcept(user,"QUIT :%s",reason);
1201 // Q token must go to ALL servers!!!
1202 char buffer[MAXBUF];
1203 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1204 NetSendToAll(buffer);
1207 FOREACH_MOD OnUserDisconnect(user);
1211 FOREACH_MOD OnRawSocketClose(user->fd);
1214 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1215 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1218 log(DEBUG,"kqueue: Failed to remove user from queue!");
1222 struct epoll_event ev;
1223 ev.events = EPOLLIN | EPOLLET;
1224 ev.data.fd = user->fd;
1225 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1228 log(DEBUG,"epoll: List deletion failure!");
1231 user->CloseSocket();
1234 if (user->registered == 7) {
1235 purge_empty_chans(user);
1238 if (iter != clientlist.end())
1240 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1242 fd_ref_table[user->fd] = NULL;
1243 clientlist.erase(iter);
1249 int main(int argc, char** argv)
1253 log(DEBUG,"*** InspIRCd starting up!");
1254 if (!FileExists(CONFIG_FILE))
1256 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1257 log(DEFAULT,"main: no config");
1258 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1262 for (int i = 1; i < argc; i++)
1264 if (!strcmp(argv[i],"-nofork")) {
1267 if (!strcmp(argv[i],"-wait")) {
1270 if (!strcmp(argv[i],"-nolimit")) {
1275 strlcpy(MyExecutable,argv[0],MAXBUF);
1277 // initialize the lowercase mapping table
1278 for (unsigned int cn = 0; cn < 256; cn++)
1280 // lowercase the uppercase chars
1281 for (unsigned int cn = 65; cn < 91; cn++)
1282 lowermap[cn] = tolower(cn);
1283 // now replace the specific chars for scandanavian comparison
1284 lowermap[(unsigned)'['] = '{';
1285 lowermap[(unsigned)']'] = '}';
1286 lowermap[(unsigned)'\\'] = '|';
1288 if (InspIRCd(argv,argc) == ERROR)
1290 log(DEFAULT,"main: daemon function bailed");
1291 printf("ERROR: could not initialise. Shutting down.\n");
1298 template<typename T> inline string ConvToStr(const T &in)
1301 if (!(tmp << in)) return string();
1305 /* re-allocates a nick in the user_hash after they change nicknames,
1306 * returns a pointer to the new user as it may have moved */
1308 userrec* ReHashNick(char* Old, char* New)
1310 //user_hash::iterator newnick;
1311 user_hash::iterator oldnick = clientlist.find(Old);
1313 log(DEBUG,"ReHashNick: %s %s",Old,New);
1315 if (!strcasecmp(Old,New))
1317 log(DEBUG,"old nick is new nick, skipping");
1318 return oldnick->second;
1321 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1323 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1325 userrec* olduser = oldnick->second;
1326 clientlist[New] = olduser;
1327 clientlist.erase(oldnick);
1329 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1331 return clientlist[New];
1334 /* adds or updates an entry in the whowas list */
1335 void AddWhoWas(userrec* u)
1337 whowas_hash::iterator iter = whowas.find(u->nick);
1338 WhoWasUser *a = new WhoWasUser();
1339 strlcpy(a->nick,u->nick,NICKMAX);
1340 strlcpy(a->ident,u->ident,IDENTMAX);
1341 strlcpy(a->dhost,u->dhost,160);
1342 strlcpy(a->host,u->host,160);
1343 strlcpy(a->fullname,u->fullname,MAXGECOS);
1344 strlcpy(a->server,u->server,256);
1345 a->signon = u->signon;
1347 /* MAX_WHOWAS: max number of /WHOWAS items
1348 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1349 * can be replaced by a newer one
1352 if (iter == whowas.end())
1354 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1356 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1358 // 3600 seconds in an hour ;)
1359 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1361 // delete the old one
1362 if (i->second) delete i->second;
1363 // replace with new one
1365 log(DEBUG,"added WHOWAS entry, purged an old record");
1369 // no space left and user doesnt exist. Don't leave ram in use!
1370 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1375 log(DEBUG,"added fresh WHOWAS entry");
1376 whowas[a->nick] = a;
1381 log(DEBUG,"updated WHOWAS entry");
1382 if (iter->second) delete iter->second;
1388 /* add a client connection to the sockets list */
1389 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1393 user_hash::iterator iter;
1395 tempnick = ConvToStr(socket) + "-unknown";
1396 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1398 iter = clientlist.find(tempnick);
1401 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1402 // using one as a registered connection. As theyre per fd, we can also safely assume
1403 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1404 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1405 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1406 // issue in earlier alphas/betas
1407 if (iter != clientlist.end())
1409 userrec* goner = iter->second;
1411 clientlist.erase(iter);
1415 * It is OK to access the value here this way since we know
1416 * it exists, we just created it above.
1418 * At NO other time should you access a value in a map or a
1419 * hash_map this way.
1421 clientlist[tempnick] = new userrec();
1423 NonBlocking(socket);
1424 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1426 clientlist[tempnick]->fd = socket;
1427 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1428 strlcpy(clientlist[tempnick]->host, host,160);
1429 strlcpy(clientlist[tempnick]->dhost, host,160);
1430 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1431 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1432 clientlist[tempnick]->registered = 0;
1433 clientlist[tempnick]->signon = TIME+dns_timeout;
1434 clientlist[tempnick]->lastping = 1;
1435 clientlist[tempnick]->port = port;
1436 strlcpy(clientlist[tempnick]->ip,ip,16);
1438 // set the registration timeout for this user
1439 unsigned long class_regtimeout = 90;
1440 int class_flood = 0;
1441 long class_threshold = 5;
1442 long class_sqmax = 262144; // 256kb
1443 long class_rqmax = 4096; // 4k
1445 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1447 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1449 class_regtimeout = (unsigned long)i->registration_timeout;
1450 class_flood = i->flood;
1451 clientlist[tempnick]->pingmax = i->pingtime;
1452 class_threshold = i->threshold;
1453 class_sqmax = i->sendqmax;
1454 class_rqmax = i->recvqmax;
1459 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1460 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1461 clientlist[tempnick]->flood = class_flood;
1462 clientlist[tempnick]->threshold = class_threshold;
1463 clientlist[tempnick]->sendqmax = class_sqmax;
1464 clientlist[tempnick]->recvqmax = class_rqmax;
1466 for (int i = 0; i < MAXCHANS; i++)
1468 clientlist[tempnick]->chans[i].channel = NULL;
1469 clientlist[tempnick]->chans[i].uc_modes = 0;
1472 if (clientlist.size() == MAXCLIENTS)
1474 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1478 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1479 // its a pretty big but for the moment valid assumption:
1480 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1481 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1482 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1483 // which for the time being is a physical impossibility (even the largest networks dont have more
1484 // than about 10,000 users on ONE server!)
1487 kill_link(clientlist[tempnick],"Server is full");
1492 char* e = matches_exception(ip);
1495 char* r = matches_zline(ip);
1498 char reason[MAXBUF];
1499 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1500 kill_link(clientlist[tempnick],reason);
1504 fd_ref_table[socket] = clientlist[tempnick];
1507 struct epoll_event ev;
1508 log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1509 ev.events = EPOLLIN | EPOLLET;
1510 ev.data.fd = socket;
1511 int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1514 log(DEBUG,"epoll: List insertion failure!");
1519 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1520 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1521 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1524 log(DEBUG,"kqueue: List insertion failure!");
1530 /* shows the message of the day, and any other on-logon stuff */
1531 void FullConnectUser(userrec* user)
1534 user->idle_lastmsg = TIME;
1535 log(DEBUG,"ConnectUser: %s",user->nick);
1537 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1539 kill_link(user,"Invalid password");
1544 kill_link(user,"Unauthorised connection");
1548 char match_against[MAXBUF];
1549 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1550 char* e = matches_exception(match_against);
1553 char* r = matches_gline(match_against);
1556 char reason[MAXBUF];
1557 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1558 kill_link_silent(user,reason);
1561 r = matches_kline(user->host);
1564 char reason[MAXBUF];
1565 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1566 kill_link_silent(user,reason);
1571 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1572 user->registered = 7;
1574 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1575 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1576 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1577 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1578 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1579 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1580 std::stringstream v;
1581 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1582 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1583 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1585 std::string data005 = v.str();
1586 FOREACH_MOD On005Numeric(data005);
1587 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1588 // so i'd better split it :)
1589 std::stringstream out(data005);
1590 std::string token = "";
1591 std::string line5 = "";
1592 int token_counter = 0;
1596 line5 = line5 + token + " ";
1598 if ((token_counter >= 13) || (out.eof() == true))
1600 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1607 char buffer[MAXBUF];
1608 snprintf(buffer,MAXBUF,"N %lu %s %s %s %s +%s %s %s :%s",(unsigned long)user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
1609 NetSendToAll(buffer);
1611 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1612 FOREACH_MOD OnUserConnect(user);
1613 FOREACH_MOD OnGlobalConnect(user);
1614 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1618 /* shows the message of the day, and any other on-logon stuff */
1619 void ConnectUser(userrec *user)
1621 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1622 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1624 FullConnectUser(user);
1628 std::string GetVersionString()
1630 char Revision[] = "$Revision$";
1631 char versiondata[MAXBUF];
1632 char *s1 = Revision;
1634 char *v2 = strtok_r(s1," ",&savept);
1636 v2 = strtok_r(s1," ",&savept);
1639 char socketengine[] = "kqueue";
1642 char socketengine[] = "select";
1645 char socketengine[] = "epoll";
1647 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1651 void handle_version(char **parameters, int pcnt, userrec *user)
1655 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1659 if (!strcmp(parameters[0],"*"))
1661 for (int j = 0; j < 32; j++)
1665 for (unsigned int x = 0; x < me[j]->connectors.size(); x++)
1667 WriteServ(user->fd,"351 %s :Server %d:%d (%s): %s",user->nick,j,x,me[j]->connectors[x].GetServerName().c_str(),me[j]->connectors[x].GetVersionString().c_str());
1673 if (match(ServerName,parameters[0]))
1675 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1678 bool displayed = false, found = false;
1679 for (int j = 0; j < 32; j++)
1683 for (unsigned int x = 0; x < me[j]->connectors.size(); x++)
1685 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1688 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1691 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1697 if ((!displayed) && (found))
1699 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1704 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1711 // calls a handler function for a command
1713 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1715 for (unsigned int i = 0; i < cmdlist.size(); i++)
1717 if (!strcasecmp(cmdlist[i].command,commandname))
1719 if (cmdlist[i].handler_function)
1721 if (pcnt>=cmdlist[i].min_params)
1723 if (strchr(user->modes,cmdlist[i].flags_needed))
1725 cmdlist[i].handler_function(parameters,pcnt,user);
1733 void DoSplitEveryone()
1735 bool go_again = true;
1739 for (int i = 0; i < 32; i++)
1743 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1745 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1748 j->CloseConnection();
1749 me[i]->connectors.erase(j);
1757 log(DEBUG,"Removed server. Will remove clients...");
1758 // iterate through the userlist and remove all users on this server.
1759 // because we're dealing with a mesh, we dont have to deal with anything
1760 // "down-route" from this server (nice huh)
1762 char reason[MAXBUF];
1766 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1768 if (strcasecmp(u->second->server,ServerName))
1770 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1771 kill_link(u->second,reason);
1777 has_been_netsplit = true;
1782 void force_nickchange(userrec* user,const char* newnick)
1789 FOREACH_RESULT(OnUserPreNick(user,newnick));
1792 kill_link(user,"Nickname collision");
1795 if (matches_qline(newnick))
1798 kill_link(user,"Nickname collision");
1806 strncpy(nick,newnick,MAXBUF);
1808 if (user->registered == 7)
1812 handle_nick(pars,1,user);
1818 int process_parameters(char **command_p,char *parameters)
1821 int q = strlen(parameters);
1824 /* no parameters, command_p invalid! */
1827 if (parameters[0] == ':')
1829 command_p[0] = parameters+1;
1834 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1836 /* only one parameter */
1837 command_p[0] = parameters;
1838 if (parameters[0] == ':')
1840 if (strchr(parameters,' ') != NULL)
1848 command_p[j++] = parameters;
1849 for (int i = 0; i <= q; i++)
1851 if (parameters[i] == ' ')
1853 command_p[j++] = parameters+i+1;
1854 parameters[i] = '\0';
1855 if (command_p[j-1][0] == ':')
1857 *command_p[j-1]++; /* remove dodgy ":" */
1859 /* parameter like this marks end of the sequence */
1863 return j; /* returns total number of items in the list */
1866 void process_command(userrec *user, char* cmd)
1870 char *command_p[127];
1871 char p[MAXBUF], temp[MAXBUF];
1872 int j, items, cmd_found;
1874 for (int i = 0; i < 127; i++)
1875 command_p[i] = NULL;
1890 int total_params = 0;
1893 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1895 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1898 // found a 'trailing', we dont count them after this.
1906 // another phidjit bug...
1907 if (total_params > 126)
1909 *(strchr(cmd,' ')) = '\0';
1910 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1914 strlcpy(temp,cmd,MAXBUF);
1916 std::string tmp = cmd;
1917 for (int i = 0; i <= MODCOUNT; i++)
1919 std::string oldtmp = tmp;
1920 modules[i]->OnServerRaw(tmp,true,user);
1923 log(DEBUG,"A Module changed the input string!");
1924 log(DEBUG,"New string: %s",tmp.c_str());
1925 log(DEBUG,"Old string: %s",oldtmp.c_str());
1929 strlcpy(cmd,tmp.c_str(),MAXBUF);
1930 strlcpy(temp,cmd,MAXBUF);
1932 if (!strchr(cmd,' '))
1934 /* no parameters, lets skip the formalities and not chop up
1936 log(DEBUG,"About to preprocess command with no params");
1938 command_p[0] = NULL;
1940 for (unsigned int i = 0; i <= strlen(cmd); i++)
1942 cmd[i] = toupper(cmd[i]);
1950 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1951 for (unsigned int i = 0; i < strlen(temp); i++)
1953 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1959 /* split the full string into a command plus parameters */
1963 if (strchr(cmd,' '))
1965 for (unsigned int i = 0; i <= strlen(cmd); i++)
1967 /* capitalise the command ONLY, leave params intact */
1968 cmd[i] = toupper(cmd[i]);
1969 /* are we nearly there yet?! :P */
1973 parameters = cmd+i+1;
1981 for (unsigned int i = 0; i <= strlen(cmd); i++)
1983 cmd[i] = toupper(cmd[i]);
1990 if (strlen(command)>MAXCOMMAND)
1992 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1996 for (unsigned int x = 0; x < strlen(command); x++)
1998 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2000 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2002 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2005 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2012 for (unsigned int i = 0; i != cmdlist.size(); i++)
2014 if (cmdlist[i].command[0])
2016 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2022 items = process_parameters(command_p,parameters);
2027 command_p[0] = NULL;
2033 command_p[0] = NULL;
2038 /* activity resets the ping pending timer */
2039 user->nping = TIME + user->pingmax;
2040 if ((items) < cmdlist[i].min_params)
2042 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2043 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2046 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2048 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2049 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2053 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2055 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2056 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2060 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2062 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2064 if ((!isnick(user->nick)) || (user->registered != 7))
2066 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2067 WriteServ(user->fd,"451 %s :You have not registered",command);
2071 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2073 std::stringstream dcmds(DisabledCommands);
2074 while (!dcmds.eof())
2076 std::string thiscmd;
2078 if (!strcasecmp(thiscmd.c_str(),command))
2080 // command is disabled!
2081 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2086 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2088 if (cmdlist[i].handler_function)
2091 /* ikky /stats counters */
2094 cmdlist[i].use_count++;
2095 cmdlist[i].total_bytes+=strlen(temp);
2099 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2100 if (MOD_RESULT == 1) {
2104 /* WARNING: nothing may come after the
2105 * command handler call, as the handler
2106 * may free the user structure! */
2108 cmdlist[i].handler_function(command_p,items,user);
2114 WriteServ(user->fd,"451 %s :You have not registered",command);
2122 if ((!cmd_found) && (user))
2125 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2129 bool removecommands(const char* source)
2131 bool go_again = true;
2135 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2137 if (!strcmp(i->source,source))
2139 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2150 void process_buffer(const char* cmdbuf,userrec *user)
2154 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2160 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2167 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2169 strlcpy(cmd,cmdbuf,MAXBUF);
2174 int sl = strlen(cmd)-1;
2175 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2180 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2185 while (cmd[sl] == ' ') // strip trailing spaces
2195 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2197 if ((user) && (cmd))
2199 process_command(user,cmd);
2203 void DoSync(serverrec* serv, char* tcp_host)
2206 log(DEBUG,"Sending sync");
2207 // send start of sync marker: Y <timestamp>
2208 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2209 // except the ones its receiving it from.
2210 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2211 serv->SendPacket(data,tcp_host);
2212 // send users and channels
2214 NetSendMyRoutingTable();
2216 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2217 for (int j = 0; j < 32; j++)
2221 for (unsigned int k = 0; k < me[j]->connectors.size(); k++)
2223 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2225 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2226 serv->SendPacket(data,tcp_host);
2232 // send our version for the remote side to cache
2233 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2234 serv->SendPacket(data,tcp_host);
2236 // sync the users and channels, give the modules a look-in.
2237 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2239 snprintf(data,MAXBUF,"%s N %lu %s %s %s %s +%s %s %s :%s",CreateSum().c_str(),(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
2240 serv->SendPacket(data,tcp_host);
2241 if (strchr(u->second->modes,'o'))
2243 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2244 serv->SendPacket(data,tcp_host);
2246 for (int i = 0; i <= MODCOUNT; i++)
2248 string_list l = modules[i]->OnUserSync(u->second);
2249 for (unsigned int j = 0; j < l.size(); j++)
2251 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2252 serv->SendPacket(data,tcp_host);
2255 char* chl = chlist(u->second,u->second);
2258 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2259 serv->SendPacket(data,tcp_host);
2262 // send channel modes, topics etc...
2263 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2265 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2266 serv->SendPacket(data,tcp_host);
2267 for (int i = 0; i <= MODCOUNT; i++)
2269 string_list l = modules[i]->OnChannelSync(c->second);
2270 for (unsigned int j = 0; j < l.size(); j++)
2272 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2273 serv->SendPacket(data,tcp_host);
2276 if (c->second->topic[0])
2278 snprintf(data,MAXBUF,"%s T %lu %s %s :%s",CreateSum().c_str(),(unsigned long)c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2279 serv->SendPacket(data,tcp_host);
2281 // send current banlist
2283 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2285 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2286 serv->SendPacket(data,tcp_host);
2289 // sync global zlines, glines, etc
2290 sync_xlines(serv,tcp_host);
2292 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2293 serv->SendPacket(data,tcp_host);
2294 log(DEBUG,"Sent sync");
2295 // ircd sends its serverlist after the end of sync here
2299 void NetSendMyRoutingTable()
2301 // send out a line saying what is reachable to us.
2302 // E.g. if A is linked to B C and D, send out:
2304 // if its only linked to B and D send out:
2306 // if it has no links, dont even send out the line at all.
2307 char buffer[MAXBUF];
2308 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2309 bool sendit = false;
2310 for (int i = 0; i < 32; i++)
2314 for (unsigned int j = 0; j < me[i]->connectors.size(); j++)
2316 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2318 strlcat(buffer," ",MAXBUF);
2319 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2326 NetSendToAll(buffer);
2330 void DoSplit(const char* params)
2332 bool go_again = true;
2336 for (int i = 0; i < 32; i++)
2340 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2342 if (!strcasecmp(j->GetServerName().c_str(),params))
2345 j->CloseConnection();
2346 me[i]->connectors.erase(j);
2354 log(DEBUG,"Removed server. Will remove clients...");
2355 // iterate through the userlist and remove all users on this server.
2356 // because we're dealing with a mesh, we dont have to deal with anything
2357 // "down-route" from this server (nice huh)
2359 char reason[MAXBUF];
2360 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2364 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2366 if (!strcasecmp(u->second->server,params))
2368 kill_link(u->second,reason);
2374 has_been_netsplit = true;
2377 // removes a server. Will NOT remove its users!
2379 void RemoveServer(const char* name)
2381 bool go_again = true;
2385 for (int i = 0; i < 32; i++)
2389 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2391 if (!strcasecmp(j->GetServerName().c_str(),name))
2394 j->CloseConnection();
2395 me[i]->connectors.erase(j);
2406 char MODERR[MAXBUF];
2413 void erase_factory(int j)
2416 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2421 factory.push_back(NULL);
2428 void erase_module(int j)
2431 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2437 modules.push_back(NULL);
2443 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2447 module_names.erase(v);
2455 bool UnloadModule(const char* filename)
2457 std::string filename_str = filename;
2458 for (unsigned int j = 0; j != module_names.size(); j++)
2460 if (module_names[j] == filename_str)
2462 if (modules[j]->GetVersion().Flags & VF_STATIC)
2464 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2465 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2469 log(DEBUG,"Deleting module...");
2471 log(DEBUG,"Erasing module entry...");
2473 log(DEBUG,"Removing dependent commands...");
2474 removecommands(filename);
2475 log(DEFAULT,"Module %s unloaded",filename);
2480 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2481 snprintf(MODERR,MAXBUF,"Module not loaded");
2485 bool LoadModule(const char* filename)
2487 char modfile[MAXBUF];
2489 snprintf(modfile,MAXBUF,"%s",filename);
2491 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2493 std::string filename_str = filename;
2495 if (!DirValid(modfile))
2497 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2498 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2502 log(DEBUG,"Loading module: %s",modfile);
2504 if (FileExists(modfile))
2507 for (unsigned int j = 0; j < module_names.size(); j++)
2509 if (module_names[j] == filename_str)
2511 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2512 snprintf(MODERR,MAXBUF,"Module already loaded");
2516 ircd_module* a = new ircd_module(modfile);
2517 factory[MODCOUNT+1] = a;
2518 if (factory[MODCOUNT+1]->LastError())
2520 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2521 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2525 if (factory[MODCOUNT+1]->factory)
2527 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2528 modules[MODCOUNT+1] = m;
2529 /* save the module and the module's classfactory, if
2530 * this isnt done, random crashes can occur :/ */
2531 module_names.push_back(filename);
2535 log(DEFAULT,"Unable to load %s",modfile);
2536 snprintf(MODERR,MAXBUF,"Factory function failed!");
2543 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2544 snprintf(MODERR,MAXBUF,"Module file could not be found");
2553 bool GotServer(std::string name)
2555 for (int j = 0; j < 32; j++)
2559 for (unsigned int k = 0; k < me[j]->connectors.size(); k++)
2561 if (name == me[j]->connectors[k].GetServerName())
2572 int InspIRCd(char** argv, int argc)
2574 struct sockaddr_in client,server;
2575 char addrs[MAXBUF][255];
2576 int incomingSockfd, result = TRUE;
2580 int selectResult = 0, selectResult2 = 0;
2583 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2586 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2587 log_file = fopen(logpath.c_str(),"a+");
2590 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2595 printf("Logging to ircd.log...\n");
2597 printf("Logging to %s...\n",logpath.c_str());
2600 log(DEFAULT,"$Id$");
2603 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2605 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2607 SetupCommandTable();
2608 log(DEBUG,"InspIRCd: startup: default command table set up");
2610 ReadConfig(true,NULL);
2613 printf("WARNING: %s\n\n",DieValue);
2614 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2617 log(DEBUG,"InspIRCd: startup: read config");
2619 AddServerName(ServerName);
2621 int clientportcount = 0, serverportcount = 0;
2623 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2625 ConfValue("bind","port",count,configToken,&config_f);
2626 ConfValue("bind","address",count,Addr,&config_f);
2627 ConfValue("bind","type",count,Type,&config_f);
2628 if (!strcmp(Type,"servers"))
2630 char Default[MAXBUF];
2631 strcpy(Default,"no");
2632 ConfValue("bind","default",count,Default,&config_f);
2633 if (strchr(Default,'y'))
2635 defaultRoute = serverportcount;
2636 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2638 me[serverportcount] = new serverrec(ServerName,100L,false);
2639 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2641 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2642 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2651 ports[clientportcount] = atoi(configToken);
2652 strlcpy(addrs[clientportcount],Addr,256);
2655 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2657 portCount = clientportcount;
2658 SERVERportCount = serverportcount;
2660 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2661 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2665 /* BugFix By Craig! :p */
2667 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2669 ConfValue("module","name",count,configToken,&config_f);
2670 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2671 if (!LoadModule(configToken))
2673 log(DEFAULT,"Exiting due to a module loader error.");
2674 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2678 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2680 startup_time = time(NULL);
2683 ConfValue("pid","file",0,PID,&config_f);
2684 // write once here, to try it out and make sure its ok
2687 /* setup select call */
2689 FD_ZERO(&selectFds);
2691 log(DEBUG,"InspIRCd: startup: zero selects");
2692 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2694 for (count = 0; count < portCount; count++)
2696 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2698 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2701 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2703 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2705 else /* well we at least bound to one socket so we'll continue */
2711 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2713 /* if we didn't bind to anything then abort */
2714 if (boundPortCount == 0)
2716 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2717 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2722 printf("\nInspIRCd is now running!\n");
2726 log(VERBOSE,"Not forking as -nofork was specified");
2730 if (DaemonSeed() == ERROR)
2732 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2733 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2738 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2743 if ((kq == -1) || (lkq == -1) || (skq == -1))
2745 log(DEFAULT,"main: kqueue() failed!");
2746 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2752 ep = epoll_create(MAXCLIENTS);
2753 lep = epoll_create(32);
2754 sep = epoll_create(128);
2755 if ((ep == -1) || (lep == -1) || (sep == -1))
2757 log(DEFAULT,"main: epoll_create() failed!");
2758 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2764 log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2765 for (count = 0; count < boundPortCount; count++)
2767 struct epoll_event ev;
2768 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2769 ev.events = EPOLLIN | EPOLLET;
2770 ev.data.fd = openSockfd[count];
2771 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2774 log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2775 printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2780 for (int t = 0; t != SERVERportCount; t++)
2782 struct epoll_event ev;
2783 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2784 ev.events = EPOLLIN | EPOLLET;
2785 ev.data.fd = me[t]->fd;
2786 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2789 log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2790 printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2796 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2797 for (count = 0; count < boundPortCount; count++)
2800 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2801 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2802 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2805 log(DEFAULT,"main: add listen ports to kqueue failed!");
2806 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2810 for (int t = 0; t != SERVERportCount; t++)
2815 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2816 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2817 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2820 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2821 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2829 log(DEFAULT,"Using standard select socket engine.");
2835 length = sizeof (client);
2836 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2840 struct kevent ke_list[33];
2844 struct epoll_event event[33];
2851 tvs.tv_usec = 10000L;
2854 tv.tv_usec = 10000L;
2857 tval.tv_usec = 10000L;
2859 int total_in_this_set = 0;
2860 int i = 0, v = 0, j = 0, cycle_iter = 0;
2861 bool expire_run = false;
2863 /* main loop, this never returns */
2866 #ifdef _POSIX_PRIORITY_SCHEDULING
2872 // we only read time() once per iteration rather than tons of times!
2878 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2879 // them in a list, then reap the list every second or so.
2880 if (((TIME % 5) == 0) && (!expire_run))
2882 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2884 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2885 ConfValue("link","name",i,Link_ServerName,&config_f);
2886 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2887 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2889 autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2890 if (a != autoconns.end())
2892 if (TIME > a->second)
2894 ConnectServer(Link_ServerName,NULL);
2895 a->second = TIME + atoi(Link_AConn);
2902 FOREACH_MOD OnBackgroundTimer(TIME);
2906 if ((TIME % 5) == 1)
2909 // fix by brain - this must be below any manipulation of the hashmap by modules
2910 user_hash::iterator count2 = clientlist.begin();
2913 i = epoll_wait(sep, event, 1, EP_DELAY);
2916 log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2917 for (int x = 0; x != SERVERportCount; x++)
2919 if ((me[x]) && ((unsigned)event[0].data.fd == (unsigned)me[x]->fd))
2924 ts.tv_nsec = 30000L;
2925 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2928 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2929 for (int x = 0; x != SERVERportCount; x++)
2931 if ((me[x]) && ((unsigned)ke.ident == (unsigned)me[x]->fd))
2936 FD_ZERO(&serverfds);
2937 for (int x = 0; x != SERVERportCount; x++)
2940 FD_SET(me[x]->fd, &serverfds);
2942 tvs.tv_usec = 30000L;
2944 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2947 for (int x = 0; x != SERVERportCount; x++)
2949 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2952 char remotehost[MAXBUF],resolved[MAXBUF];
2953 length = sizeof (client);
2954 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2955 if (incomingSockfd != -1)
2957 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2958 if(CleanAndResolve(resolved, remotehost) != TRUE)
2960 strlcpy(resolved,remotehost,MAXBUF);
2962 // add to this connections ircd_connector vector
2963 // *FIX* - we need the LOCAL port not the remote port in &client!
2964 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2970 std::deque<std::string> msgs;
2971 std::deque<std::string> sums;
2972 for (int x = 0; x < SERVERportCount; x++)
2975 me[x]->FlushWriteBuffers();
2978 while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2980 has_been_netsplit = false;
2981 for (unsigned int ctr = 0; ctr < msgs.size(); ctr++)
2983 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2984 strlcpy(tcp_sum,sums[ctr].c_str(),MAXBUF);
2985 log(DEBUG,"Processing: %s",tcp_msg);
2988 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2991 // during a netburst, send all data to all other linked servers
2992 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2994 if (is_uline(tcp_host))
2996 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2998 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
3002 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
3004 std::string msg = tcp_msg;
3005 FOREACH_MOD OnPacketReceive(msg,tcp_host);
3006 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
3008 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
3009 if (!me[x]->FindHost(tcp_host))
3011 log(DEBUG,"Connector gone, bailing!");
3019 while (count2 != clientlist.end())
3025 total_in_this_set = 0;
3027 user_hash::iterator xcount = count2;
3028 user_hash::iterator endingiter = count2;
3030 if (count2 == clientlist.end()) break;
3032 userrec* curr = NULL;
3035 curr = count2->second;
3037 if ((long)curr == -1)
3040 if ((curr) && (curr->fd != 0))
3042 #ifdef _POSIX_PRIORITY_SCHEDULING
3045 // assemble up to 64 sockets into an fd_set
3046 // to implement a pooling mechanism.
3048 // This should be up to 64x faster than the
3049 // old implementation.
3051 while (total_in_this_set < 1024)
3053 if (count2 != clientlist.end())
3055 curr = count2->second;
3056 if ((long)curr == -1)
3058 int currfd = curr->fd;
3059 // we don't check the state of remote users.
3060 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3062 curr->FlushWriteBuf();
3063 if (curr->GetWriteError() != "")
3065 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3066 kill_link(curr,curr->GetWriteError().c_str());
3070 FD_SET (curr->fd, &sfd);
3072 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3073 // their connection class.
3074 if ((TIME > curr->timeout) && (curr->registered != 7))
3076 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3077 kill_link(curr,"Registration timeout");
3080 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3082 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3083 curr->dns_done = true;
3085 FullConnectUser(curr);
3086 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3089 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3091 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3092 FullConnectUser(curr);
3093 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3096 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3098 if ((!curr->lastping) && (curr->registered == 7))
3100 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3101 kill_link(curr,"Ping timeout");
3104 Write(curr->fd,"PING :%s",ServerName);
3105 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3107 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3111 total_in_this_set++;
3115 endingiter = count2;
3116 count2 = xcount; // roll back to where we were
3118 // 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.
3119 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3121 if (cycle_iter > 20) while (count2 != clientlist.end())
3124 if (count2 != clientlist.end())
3126 curr = count2->second;
3127 if ((long)curr == -1)
3129 int currfd = curr->fd;
3130 // we don't check the state of remote users.
3131 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3134 curr->FlushWriteBuf();
3135 if (curr->GetWriteError() != "")
3137 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3138 kill_link(curr,curr->GetWriteError().c_str());
3142 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3143 // their connection class.
3144 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
3146 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3147 kill_link(curr,"Registration timeout");
3151 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3153 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3154 curr->dns_done = true;
3156 FullConnectUser(curr);
3157 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3160 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3162 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3163 FullConnectUser(curr);
3164 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3167 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3169 if ((!curr->lastping) && (curr->registered == 7))
3171 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3172 kill_link(curr,"Ping timeout");
3175 Write(curr->fd,"PING :%s",ServerName);
3176 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3178 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3185 // increment the counter right to the end of the list, as kqueue processes everything in one go
3190 int i = epoll_wait(ep, event, 1, 5);
3193 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3194 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3195 userrec* cu = fd_ref_table[event[0].data.fd];
3200 // for now, we only read 1 event. We could read soooo many more :)
3201 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3204 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3205 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3206 userrec* cu = fd_ref_table[ke.ident];
3210 tval.tv_usec = 1000L;
3211 selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3212 // now loop through all of the items in this pool if any are waiting
3213 if ((selectResult2 > 0) && (xcount != clientlist.end()))
3214 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3216 // SELECT: we have to iterate...
3217 if (count2a == clientlist.end())
3219 userrec* cu = count2a->second;
3222 #ifdef _POSIX_PRIORITY_SCHEDULING
3227 // EPOLL: We already know we have a valid FD. No checks needed.
3228 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3231 // KQUEUE: We already know we have a valid FD. No checks needed.
3232 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3235 // SELECT: We don't know if our FD is valid.
3236 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3239 log(DEBUG,"Data waiting on socket %d",cu->fd);
3242 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3245 result = cu->ReadData(data, 65535);
3247 else result = result2;
3248 log(DEBUG,"Read result: %d",result);
3251 statsRecv += result;
3252 // perform a check on the raw buffer as an array (not a string!) to remove
3253 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3254 // hopefully this should stop even more people whining about "Unknown command: *"
3255 for (int checker = 0; checker < result; checker++)
3257 if ((data[checker] == 0) || (data[checker] == 7))
3258 data[checker] = ' ';
3261 data[result] = '\0';
3262 userrec* current = cu;
3263 int currfd = current->fd;
3265 // add the data to the users buffer
3267 if (!current->AddBuffer(data))
3269 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3270 if (current->registered == 7)
3272 kill_link(current,"RecvQ exceeded");
3276 WriteOpers("*** Excess flood from %s",current->ip);
3277 log(DEFAULT,"Excess flood from: %s",current->ip);
3278 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3283 if (current->recvq.length() > (unsigned)NetBufferSize)
3285 if (current->registered == 7)
3287 kill_link(current,"RecvQ exceeded");
3291 WriteOpers("*** Excess flood from %s",current->ip);
3292 log(DEFAULT,"Excess flood from: %s",current->ip);
3293 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3298 // while there are complete lines to process...
3299 while (current->BufferIsReady())
3302 if (TIME > current->reset_due)
3304 current->reset_due = TIME + current->threshold;
3305 current->lines_in = 0;
3307 current->lines_in++;
3308 if (current->lines_in > current->flood)
3310 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3311 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3312 kill_link(current,"Excess flood");
3315 if ((floodlines > current->flood) && (current->flood != 0))
3317 if (current->registered == 7)
3319 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3320 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3321 kill_link(current,"Excess flood");
3325 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3330 char sanitized[MAXBUF];
3331 // use GetBuffer to copy single lines into the sanitized string
3332 std::string single_line = current->GetBuffer();
3333 current->bytes_in += single_line.length();
3335 if (single_line.length()>512)
3337 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3338 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3339 kill_link(current,"Excess flood");
3342 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3345 userrec* old_comp = fd_ref_table[currfd];
3346 // we're gonna re-scan to check if the nick is gone, after every
3347 // command - if it has, we're gonna bail
3348 process_buffer(sanitized,current);
3349 // look for the user's record in case it's changed... if theyve quit,
3350 // we cant do anything more with their buffer, so bail.
3351 // there used to be an ugly, slow loop here. Now we have a reference
3352 // table, life is much easier (and FASTER)
3353 userrec* new_comp = fd_ref_table[currfd];
3354 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3362 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3364 log(DEBUG,"killing: %s",cu->nick);
3365 kill_link(cu,strerror(errno));
3369 // result EAGAIN means nothing read
3370 if (result == EAGAIN)
3380 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3381 kill_link(cu,"Client exited");
3382 // must bail here? kill_link removes the hash, corrupting the iterator
3383 log(DEBUG,"Bailing from client exit");
3389 else if (result > 0)
3394 for (int q = 0; q < total_in_this_set; q++)
3400 #ifdef _POSIX_PRIORITY_SCHEDULING
3405 // set up select call
3406 for (count = 0; count < boundPortCount; count++)
3408 FD_SET (openSockfd[count], &selectFds);
3411 tv.tv_usec = 30000L;
3412 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3414 /* select is reporting a waiting socket. Poll them all to find out which */
3415 if (selectResult > 0)
3417 for (count = 0; count < boundPortCount; count++)
3419 if (FD_ISSET (openSockfd[count], &selectFds))
3424 ts.tv_nsec = 30000L;
3425 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3426 if (i > 0) for (j = 0; j < i; j++)
3428 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3429 // this isnt as efficient as it could be, we could create a reference table
3430 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3431 // number of listening ports on the average ircd is a small number (less than 20)
3432 // compared to the number of clients (possibly over 2000)
3433 for (count = 0; count < boundPortCount; count++)
3435 if ((unsigned)ke_list[j].ident == (unsigned)openSockfd[count])
3439 i = epoll_wait(lep, event, 32, EP_DELAY);
3440 if (i > 0) for (j = 0; j < i; j++)
3442 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3443 for (count = 0; count < boundPortCount; count++)
3445 if ((unsigned)event[j].data.fd == (unsigned)openSockfd[count])
3448 char target[MAXBUF], resolved[MAXBUF];
3449 length = sizeof (client);
3450 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3452 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3453 strlcpy (resolved, target, MAXBUF);
3455 if (incomingSockfd < 0)
3457 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3458 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3463 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3465 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3466 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3473 #ifdef _POSIX_PRIORITY_SCHEDULING
3479 close (incomingSockfd);