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! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.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 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
123 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
124 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
125 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
126 typedef std::deque<command_t> command_table;
127 typedef std::map<std::string,time_t> autoconnects;
129 // This table references users by file descriptor.
130 // its an array to make it VERY fast, as all lookups are referenced
131 // by an integer, meaning there is no need for a scan/search operation.
132 userrec* fd_ref_table[65536];
134 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
140 user_hash clientlist;
143 command_table cmdlist;
144 autoconnects autoconns;
151 struct linger linger = { 0 };
152 char MyExecutable[1024];
153 int boundPortCount = 0;
154 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
155 int defaultRoute = 0;
156 char ModPath[MAXBUF];
160 int has_channel(userrec *u, chanrec *c);
161 int usercount(chanrec *c);
162 int usercount_i(chanrec *c);
163 char* Passwd(userrec *user);
164 bool IsDenied(userrec *user);
165 void AddWhoWas(userrec* u);
167 std::vector<long> auth_cookies;
168 std::stringstream config_f(stringstream::in | stringstream::out);
170 std::vector<userrec*> all_opers;
174 void AddOper(userrec* user)
176 log(DEBUG,"Oper added to optimization list");
177 all_opers.push_back(user);
180 void DeleteOper(userrec* user)
182 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
186 log(DEBUG,"Oper removed from optimization list");
193 std::string GetRevision()
195 char Revision[] = "$Revision$";
198 char *v2 = strtok_r(s1," ",&savept);
200 v2 = strtok_r(s1," ",&savept);
202 return std::string(v2);
206 std::string getservername()
211 std::string getserverdesc()
216 std::string getnetworkname()
221 std::string getadminname()
226 std::string getadminemail()
231 std::string getadminnick()
236 void ReadConfig(bool bail, userrec* user)
238 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
239 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
241 std::stringstream errstr;
243 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
248 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
256 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
257 while (!errstr.eof())
259 errstr.getline(dataline,1024);
260 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
265 WriteOpers("There were errors in the configuration file:",user->nick);
266 while (!errstr.eof())
268 errstr.getline(dataline,1024);
269 WriteOpers(dataline);
276 ConfValue("server","name",0,ServerName,&config_f);
277 ConfValue("server","description",0,ServerDesc,&config_f);
278 ConfValue("server","network",0,Network,&config_f);
279 ConfValue("admin","name",0,AdminName,&config_f);
280 ConfValue("admin","email",0,AdminEmail,&config_f);
281 ConfValue("admin","nick",0,AdminNick,&config_f);
282 ConfValue("files","motd",0,motd,&config_f);
283 ConfValue("files","rules",0,rules,&config_f);
284 ConfValue("power","diepass",0,diepass,&config_f);
285 ConfValue("power","pause",0,pauseval,&config_f);
286 ConfValue("power","restartpass",0,restartpass,&config_f);
287 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
288 ConfValue("die","value",0,DieValue,&config_f);
289 ConfValue("options","loglevel",0,dbg,&config_f);
290 ConfValue("options","netbuffersize",0,NB,&config_f);
291 ConfValue("options","maxwho",0,MW,&config_f);
292 ConfValue("options","allowhalfop",0,AH,&config_f);
293 ConfValue("options","allowprotect",0,AP,&config_f);
294 ConfValue("options","allowfounder",0,AF,&config_f);
295 ConfValue("dns","server",0,DNSServer,&config_f);
296 ConfValue("dns","timeout",0,DNT,&config_f);
297 ConfValue("options","moduledir",0,ModPath,&config_f);
298 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
299 ConfValue("options","somaxconn",0,MCON,&config_f);
301 MaxConn = atoi(MCON);
302 if (MaxConn > SOMAXCONN)
303 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
304 NetBufferSize = atoi(NB);
305 MaxWhoResults = atoi(MW);
306 dns_timeout = atoi(DNT);
312 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
314 strlcpy(ModPath,MOD_PATH,MAXBUF);
315 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
316 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
317 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
318 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
320 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
321 NetBufferSize = 10240;
323 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
325 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
328 if (!strcmp(dbg,"debug"))
330 if (!strcmp(dbg,"verbose"))
332 if (!strcmp(dbg,"default"))
334 if (!strcmp(dbg,"sparse"))
336 if (!strcmp(dbg,"none"))
339 log(DEFAULT,"Reading message of the day...");
340 readfile(RULES,rules);
341 log(DEFAULT,"Reading connect classes...");
343 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
346 ConfValue("connect","allow",i,Value,&config_f);
347 ConfValue("connect","timeout",i,timeout,&config_f);
348 ConfValue("connect","flood",i,flood,&config_f);
349 ConfValue("connect","pingfreq",i,pfreq,&config_f);
350 ConfValue("connect","threshold",i,thold,&config_f);
351 ConfValue("connect","sendq",i,sqmax,&config_f);
352 ConfValue("connect","recvq",i,rqmax,&config_f);
355 strlcpy(c.host,Value,MAXBUF);
357 strlcpy(Value,"",MAXBUF);
358 ConfValue("connect","password",i,Value,&config_f);
359 strlcpy(c.pass,Value,MAXBUF);
360 c.registration_timeout = 90; // default is 2 minutes
362 c.flood = atoi(flood);
364 c.sendqmax = 262144; // 256k
365 c.recvqmax = 4096; // 4k
368 c.threshold = atoi(thold);
372 c.sendqmax = atoi(sqmax);
376 c.recvqmax = atoi(rqmax);
380 c.registration_timeout = atoi(timeout);
384 c.pingtime = atoi(pfreq);
386 Classes.push_back(c);
387 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);
391 ConfValue("connect","deny",i,Value,&config_f);
392 strlcpy(c.host,Value,MAXBUF);
394 Classes.push_back(c);
395 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
399 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
400 read_xline_defaults();
401 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
404 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
406 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
407 ConfValue("link","name",i,Link_ServerName,&config_f);
408 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
409 if (strcmp(Link_AConn,""))
411 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
416 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
419 log(DEFAULT,"Adding and removing modules due to rehash...");
421 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
423 // store the old module names
424 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
426 old_module_names.push_back(*t);
429 // get the new module names
430 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
432 ConfValue("module","name",count2,Value,&config_f);
433 new_module_names.push_back(Value);
436 // now create a list of new modules that are due to be loaded
437 // and a seperate list of modules which are due to be unloaded
438 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
441 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
447 added_modules.push_back(*_new);
449 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
452 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
458 removed_modules.push_back(*oldm);
460 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
462 int rem = 0, add = 0;
463 if (!removed_modules.empty())
464 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
466 if (UnloadModule(removing->c_str()))
468 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
469 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
474 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
477 if (!added_modules.empty())
478 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
480 if (LoadModule(adding->c_str()))
482 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
483 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
488 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
491 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());
496 /* add a channel to a user, creating the record for it if needed and linking
497 * it to the user record */
499 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
501 if ((!user) || (!cn))
503 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
511 strncpy(cname,cn,MAXBUF);
513 // we MUST declare this wherever we use FOREACH_RESULT
516 if (strlen(cname) > CHANMAX-1)
518 cname[CHANMAX-1] = '\0';
521 log(DEBUG,"add_channel: %s %s",user->nick,cname);
523 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
525 return NULL; // already on the channel!
529 if (!FindChan(cname))
532 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
533 if (MOD_RESULT == 1) {
537 /* create a new one */
538 log(DEBUG,"add_channel: creating: %s",cname);
540 chanlist[cname] = new chanrec();
542 strlcpy(chanlist[cname]->name, cname,CHANMAX);
543 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
544 chanlist[cname]->created = TIME;
545 strcpy(chanlist[cname]->topic, "");
546 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
547 chanlist[cname]->topicset = 0;
548 Ptr = chanlist[cname];
549 log(DEBUG,"add_channel: created: %s",cname);
550 /* set created to 2 to indicate user
551 * is the first in the channel
552 * and should be given ops */
558 /* channel exists, just fish out a pointer to its struct */
559 Ptr = FindChan(cname);
562 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
564 // the override flag allows us to bypass channel modes
565 // and bans (used by servers)
566 if ((!override) || (!strcasecmp(user->server,ServerName)))
568 log(DEBUG,"Not overriding...");
570 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
571 if (MOD_RESULT == 1) {
574 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
578 log(DEBUG,"add_channel: checking key, invite, etc");
580 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
585 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
588 log(DEBUG,"add_channel: no key given in JOIN");
589 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
594 if (strcasecmp(key,Ptr->key))
596 log(DEBUG,"add_channel: bad key given in JOIN");
597 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
602 log(DEBUG,"add_channel: no key");
605 FOREACH_RESULT(OnCheckInvite(user, Ptr));
608 if (Ptr->binarymodes & CM_INVITEONLY)
610 log(DEBUG,"add_channel: channel is +i");
611 if (user->IsInvited(Ptr->name))
613 /* user was invited to channel */
614 /* there may be an optional channel NOTICE here */
618 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
622 log(DEBUG,"add_channel: channel is not +i");
625 FOREACH_RESULT(OnCheckLimit(user, Ptr));
630 if (usercount(Ptr) >= Ptr->limit)
632 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
637 log(DEBUG,"add_channel: about to walk banlist");
639 FOREACH_RESULT(OnCheckBan(user, Ptr));
642 /* check user against the channel banlist */
645 if (Ptr->bans.size())
647 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
649 if (match(user->GetFullHost(),i->data))
651 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
657 log(DEBUG,"add_channel: bans checked");
665 user->RemoveInvite(Ptr->name);
668 log(DEBUG,"add_channel: invites removed");
673 log(DEBUG,"Overridden checks");
681 log(DEBUG,"Passed channel checks");
683 for (int index =0; index != MAXCHANS; index++)
685 log(DEBUG,"Check location %d",index);
686 if (user->chans[index].channel == NULL)
688 log(DEBUG,"Adding into their channel list at location %d",index);
692 /* first user in is given ops */
693 user->chans[index].uc_modes = UCMODE_OP;
697 user->chans[index].uc_modes = 0;
699 user->chans[index].channel = Ptr;
700 Ptr->AddUser((char*)user);
701 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
703 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
705 // use the stamdard J token with no privilages.
709 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
713 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
715 NetSendToAll(buffer);
718 log(DEBUG,"Sent JOIN to client");
722 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
723 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
726 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
727 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
728 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
729 FOREACH_MOD OnUserJoin(user,Ptr);
733 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
734 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
738 /* remove a channel from a users record, and remove the record from memory
739 * if the channel has become empty */
741 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
743 if ((!user) || (!cname))
745 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
751 if ((!cname) || (!user))
756 Ptr = FindChan(cname);
763 FOREACH_MOD OnUserPart(user,Ptr);
764 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
766 for (int i =0; i != MAXCHANS; i++)
768 /* zap it from the channel list of the user */
769 if (user->chans[i].channel == Ptr)
773 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
778 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
779 NetSendToAll(buffer);
789 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
790 NetSendToAll(buffer);
793 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
795 user->chans[i].uc_modes = 0;
796 user->chans[i].channel = NULL;
797 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
802 Ptr->DelUser((char*)user);
804 /* if there are no users left on the channel */
807 chan_hash::iterator iter = chanlist.find(Ptr->name);
809 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
811 /* kill the record */
812 if (iter != chanlist.end())
814 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
816 chanlist.erase(iter);
822 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
824 if ((!src) || (!user) || (!Ptr) || (!reason))
826 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
830 if ((!Ptr) || (!user) || (!src))
835 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
837 if (!has_channel(user,Ptr))
839 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
844 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
845 if (MOD_RESULT == ACR_DENY)
848 if (MOD_RESULT == ACR_DEFAULT)
850 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
852 if (cstatus(src,Ptr) == STATUS_HOP)
854 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
858 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
866 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
870 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
872 for (int i =0; i != MAXCHANS; i++)
874 /* zap it from the channel list of the user */
875 if (user->chans[i].channel)
876 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
878 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
879 user->chans[i].uc_modes = 0;
880 user->chans[i].channel = NULL;
881 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
886 Ptr->DelUser((char*)user);
888 /* if there are no users left on the channel */
891 chan_hash::iterator iter = chanlist.find(Ptr->name);
893 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
895 /* kill the record */
896 if (iter != chanlist.end())
898 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
900 chanlist.erase(iter);
908 /* This function pokes and hacks at a parameter list like the following:
910 * PART #winbot,#darkgalaxy :m00!
912 * to turn it into a series of individual calls like this:
915 * PART #darkgalaxy :m00!
917 * The seperate calls are sent to a callback function provided by the caller
918 * (the caller will usually call itself recursively). The callback function
919 * must be a command handler. Calling this function on a line with no list causes
920 * no action to be taken. You must provide a starting and ending parameter number
921 * where the range of the list can be found, useful if you have a terminating
922 * parameter as above which is actually not part of the list, or parameters
923 * before the actual list as well. This code is used by many functions which
924 * can function as "one to list" (see the RFC) */
926 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
931 char blog[32][MAXBUF];
932 char blog2[32][MAXBUF];
933 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
937 for (int i = 0; i <32; i++)
940 for (int i = 0; i <32; i++)
944 for (int i = 0; i <10; i++)
953 if (pcnt > 1) /* we have a key to copy */
955 strlcpy(keystr,parameters[1],MAXBUF);
959 if (!parameters[start])
963 if (!strchr(parameters[start],','))
968 for (int i = start; i <= end; i++)
972 strlcat(plist,parameters[i],MAXBUF);
980 for (int i = 0; i < t; i++)
985 strlcpy(blog[j++],param,MAXBUF);
989 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
994 strlcpy(blog[j++],param,MAXBUF);
997 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1002 if ((joins) && (keystr))
1004 if (strchr(keystr,','))
1008 t2 = strlen(keystr);
1009 for (int i = 0; i < t2; i++)
1011 if (keystr[i] == ',')
1014 strlcpy(blog2[j++],param,MAXBUF);
1018 strlcpy(blog2[j++],param,MAXBUF);
1023 for (j = 0; j < total; j++)
1029 for (q = end; q < pcnt-1; q++)
1031 if (parameters[q+1])
1033 pars[q-end+1] = parameters[q+1];
1036 if ((joins) && (parameters[1]))
1047 /* repeatedly call the function with the hacked parameter list */
1048 if ((joins) && (pcnt > 1))
1052 // pars[1] already set up and containing key from blog2[j]
1057 pars[1] = parameters[1];
1063 fn(pars,pcnt-(end-start),u);
1072 void kill_link(userrec *user,const char* r)
1074 user_hash::iterator iter = clientlist.find(user->nick);
1076 char reason[MAXBUF];
1078 strncpy(reason,r,MAXBUF);
1080 if (strlen(reason)>MAXQUIT)
1082 reason[MAXQUIT-1] = '\0';
1085 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1086 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1087 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1089 if (user->registered == 7) {
1090 FOREACH_MOD OnUserQuit(user);
1091 WriteCommonExcept(user,"QUIT :%s",reason);
1093 // Q token must go to ALL servers!!!
1094 char buffer[MAXBUF];
1095 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1096 NetSendToAll(buffer);
1099 user->FlushWriteBuf();
1101 FOREACH_MOD OnUserDisconnect(user);
1105 FOREACH_MOD OnRawSocketClose(user->fd);
1108 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1109 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1112 log(DEBUG,"kqueue: Failed to remove user from queue!");
1116 struct epoll_event ev;
1117 ev.events = EPOLLIN | EPOLLET;
1118 ev.data.fd = user->fd;
1119 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1122 log(DEBUG,"epoll: List deletion failure!");
1125 user->CloseSocket();
1128 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1129 // if they were an oper with +s.
1130 if (user->registered == 7) {
1131 purge_empty_chans(user);
1132 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1136 if (iter != clientlist.end())
1138 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1140 fd_ref_table[user->fd] = NULL;
1141 clientlist.erase(iter);
1146 void kill_link_silent(userrec *user,const char* r)
1148 user_hash::iterator iter = clientlist.find(user->nick);
1150 char reason[MAXBUF];
1152 strncpy(reason,r,MAXBUF);
1154 if (strlen(reason)>MAXQUIT)
1156 reason[MAXQUIT-1] = '\0';
1159 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1160 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1161 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1163 user->FlushWriteBuf();
1165 if (user->registered == 7) {
1166 FOREACH_MOD OnUserQuit(user);
1167 WriteCommonExcept(user,"QUIT :%s",reason);
1169 // Q token must go to ALL servers!!!
1170 char buffer[MAXBUF];
1171 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1172 NetSendToAll(buffer);
1175 FOREACH_MOD OnUserDisconnect(user);
1179 FOREACH_MOD OnRawSocketClose(user->fd);
1182 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1183 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1186 log(DEBUG,"kqueue: Failed to remove user from queue!");
1190 struct epoll_event ev;
1191 ev.events = EPOLLIN | EPOLLET;
1192 ev.data.fd = user->fd;
1193 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1196 log(DEBUG,"epoll: List deletion failure!");
1199 user->CloseSocket();
1202 if (user->registered == 7) {
1203 purge_empty_chans(user);
1206 if (iter != clientlist.end())
1208 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1210 fd_ref_table[user->fd] = NULL;
1211 clientlist.erase(iter);
1217 int main(int argc, char** argv)
1221 log(DEBUG,"*** InspIRCd starting up!");
1222 if (!FileExists(CONFIG_FILE))
1224 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1225 log(DEFAULT,"main: no config");
1226 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1230 for (int i = 1; i < argc; i++)
1232 if (!strcmp(argv[i],"-nofork")) {
1235 if (!strcmp(argv[i],"-wait")) {
1238 if (!strcmp(argv[i],"-nolimit")) {
1243 strlcpy(MyExecutable,argv[0],MAXBUF);
1245 // initialize the lowercase mapping table
1246 for (int cn = 0; cn < 256; cn++)
1248 // lowercase the uppercase chars
1249 for (int cn = 65; cn < 91; cn++)
1250 lowermap[cn] = tolower(cn);
1251 // now replace the specific chars for scandanavian comparison
1252 lowermap['['] = '{';
1253 lowermap[']'] = '}';
1254 lowermap['\\'] = '|';
1256 if (InspIRCd(argv,argc) == ERROR)
1258 log(DEFAULT,"main: daemon function bailed");
1259 printf("ERROR: could not initialise. Shutting down.\n");
1266 template<typename T> inline string ConvToStr(const T &in)
1269 if (!(tmp << in)) return string();
1273 /* re-allocates a nick in the user_hash after they change nicknames,
1274 * returns a pointer to the new user as it may have moved */
1276 userrec* ReHashNick(char* Old, char* New)
1278 //user_hash::iterator newnick;
1279 user_hash::iterator oldnick = clientlist.find(Old);
1281 log(DEBUG,"ReHashNick: %s %s",Old,New);
1283 if (!strcasecmp(Old,New))
1285 log(DEBUG,"old nick is new nick, skipping");
1286 return oldnick->second;
1289 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1291 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1293 userrec* olduser = oldnick->second;
1294 clientlist[New] = olduser;
1295 clientlist.erase(oldnick);
1297 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1299 return clientlist[New];
1302 /* adds or updates an entry in the whowas list */
1303 void AddWhoWas(userrec* u)
1305 whowas_hash::iterator iter = whowas.find(u->nick);
1306 WhoWasUser *a = new WhoWasUser();
1307 strlcpy(a->nick,u->nick,NICKMAX);
1308 strlcpy(a->ident,u->ident,15);
1309 strlcpy(a->dhost,u->dhost,160);
1310 strlcpy(a->host,u->host,160);
1311 strlcpy(a->fullname,u->fullname,128);
1312 strlcpy(a->server,u->server,256);
1313 a->signon = u->signon;
1315 /* MAX_WHOWAS: max number of /WHOWAS items
1316 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1317 * can be replaced by a newer one
1320 if (iter == whowas.end())
1322 if (whowas.size() >= WHOWAS_MAX)
1324 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1326 // 3600 seconds in an hour ;)
1327 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1329 // delete the old one
1330 if (i->second) delete i->second;
1331 // replace with new one
1333 log(DEBUG,"added WHOWAS entry, purged an old record");
1337 // no space left and user doesnt exist. Don't leave ram in use!
1338 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1343 log(DEBUG,"added fresh WHOWAS entry");
1344 whowas[a->nick] = a;
1349 log(DEBUG,"updated WHOWAS entry");
1350 if (iter->second) delete iter->second;
1356 /* add a client connection to the sockets list */
1357 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1361 user_hash::iterator iter;
1363 tempnick = ConvToStr(socket) + "-unknown";
1364 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1366 iter = clientlist.find(tempnick);
1369 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1370 // using one as a registered connection. As theyre per fd, we can also safely assume
1371 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1372 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1373 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1374 // issue in earlier alphas/betas
1375 if (iter != clientlist.end())
1377 userrec* goner = iter->second;
1379 clientlist.erase(iter);
1383 * It is OK to access the value here this way since we know
1384 * it exists, we just created it above.
1386 * At NO other time should you access a value in a map or a
1387 * hash_map this way.
1389 clientlist[tempnick] = new userrec();
1391 NonBlocking(socket);
1392 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1394 clientlist[tempnick]->fd = socket;
1395 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1396 strncpy(clientlist[tempnick]->host, host,160);
1397 strncpy(clientlist[tempnick]->dhost, host,160);
1398 strncpy(clientlist[tempnick]->server, ServerName,256);
1399 strncpy(clientlist[tempnick]->ident, "unknown",15);
1400 clientlist[tempnick]->registered = 0;
1401 clientlist[tempnick]->signon = TIME+dns_timeout;
1402 clientlist[tempnick]->lastping = 1;
1403 clientlist[tempnick]->port = port;
1404 strncpy(clientlist[tempnick]->ip,ip,16);
1406 // set the registration timeout for this user
1407 unsigned long class_regtimeout = 90;
1408 int class_flood = 0;
1409 long class_threshold = 5;
1410 long class_sqmax = 262144; // 256kb
1411 long class_rqmax = 4096; // 4k
1413 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1415 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1417 class_regtimeout = (unsigned long)i->registration_timeout;
1418 class_flood = i->flood;
1419 clientlist[tempnick]->pingmax = i->pingtime;
1420 class_threshold = i->threshold;
1421 class_sqmax = i->sendqmax;
1422 class_rqmax = i->recvqmax;
1427 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1428 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1429 clientlist[tempnick]->flood = class_flood;
1430 clientlist[tempnick]->threshold = class_threshold;
1431 clientlist[tempnick]->sendqmax = class_sqmax;
1432 clientlist[tempnick]->recvqmax = class_rqmax;
1434 for (int i = 0; i < MAXCHANS; i++)
1436 clientlist[tempnick]->chans[i].channel = NULL;
1437 clientlist[tempnick]->chans[i].uc_modes = 0;
1440 if (clientlist.size() == MAXCLIENTS)
1442 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1446 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1447 // its a pretty big but for the moment valid assumption:
1448 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1449 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1450 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1451 // which for the time being is a physical impossibility (even the largest networks dont have more
1452 // than about 10,000 users on ONE server!)
1455 kill_link(clientlist[tempnick],"Server is full");
1460 char* e = matches_exception(ip);
1463 char* r = matches_zline(ip);
1466 char reason[MAXBUF];
1467 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1468 kill_link(clientlist[tempnick],reason);
1472 fd_ref_table[socket] = clientlist[tempnick];
1475 struct epoll_event ev;
1476 log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1477 ev.events = EPOLLIN | EPOLLET;
1478 ev.data.fd = socket;
1479 int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1482 log(DEBUG,"epoll: List insertion failure!");
1487 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1488 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1489 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1492 log(DEBUG,"kqueue: List insertion failure!");
1498 /* shows the message of the day, and any other on-logon stuff */
1499 void FullConnectUser(userrec* user)
1502 user->idle_lastmsg = TIME;
1503 log(DEBUG,"ConnectUser: %s",user->nick);
1505 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1507 kill_link(user,"Invalid password");
1512 kill_link(user,"Unauthorised connection");
1516 char match_against[MAXBUF];
1517 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1518 char* e = matches_exception(match_against);
1521 char* r = matches_gline(match_against);
1524 char reason[MAXBUF];
1525 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1526 kill_link_silent(user,reason);
1529 r = matches_kline(user->host);
1532 char reason[MAXBUF];
1533 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1534 kill_link_silent(user,reason);
1539 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1540 user->registered = 7;
1542 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1543 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1544 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1545 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1546 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1547 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1548 std::stringstream v;
1549 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1550 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1551 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1553 std::string data005 = v.str();
1554 FOREACH_MOD On005Numeric(data005);
1555 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1556 // so i'd better split it :)
1557 std::stringstream out(data005);
1558 std::string token = "";
1559 std::string line5 = "";
1560 int token_counter = 0;
1564 line5 = line5 + token + " ";
1566 if ((token_counter >= 13) || (out.eof() == true))
1568 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1575 char buffer[MAXBUF];
1576 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);
1577 NetSendToAll(buffer);
1579 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1580 FOREACH_MOD OnUserConnect(user);
1581 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1585 /* shows the message of the day, and any other on-logon stuff */
1586 void ConnectUser(userrec *user)
1588 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1589 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1591 FullConnectUser(user);
1595 std::string GetVersionString()
1597 char Revision[] = "$Revision$";
1598 char versiondata[MAXBUF];
1599 char *s1 = Revision;
1601 char *v2 = strtok_r(s1," ",&savept);
1603 v2 = strtok_r(s1," ",&savept);
1606 char socketengine[] = "kqueue";
1609 char socketengine[] = "select";
1612 char socketengine[] = "epoll";
1614 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1618 void handle_version(char **parameters, int pcnt, userrec *user)
1622 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1626 if (!strcmp(parameters[0],"*"))
1628 for (int j = 0; j < 32; j++)
1632 for (int x = 0; x < me[j]->connectors.size(); x++)
1634 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());
1640 if (match(ServerName,parameters[0]))
1642 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1645 bool displayed = false, found = false;
1646 for (int j = 0; j < 32; j++)
1650 for (int x = 0; x < me[j]->connectors.size(); x++)
1652 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1655 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1658 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1664 if ((!displayed) && (found))
1666 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1671 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1678 // calls a handler function for a command
1680 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1682 for (int i = 0; i < cmdlist.size(); i++)
1684 if (!strcasecmp(cmdlist[i].command,commandname))
1686 if (cmdlist[i].handler_function)
1688 if (pcnt>=cmdlist[i].min_params)
1690 if (strchr(user->modes,cmdlist[i].flags_needed))
1692 cmdlist[i].handler_function(parameters,pcnt,user);
1700 void DoSplitEveryone()
1702 bool go_again = true;
1706 for (int i = 0; i < 32; i++)
1710 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1712 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1715 j->CloseConnection();
1716 me[i]->connectors.erase(j);
1724 log(DEBUG,"Removed server. Will remove clients...");
1725 // iterate through the userlist and remove all users on this server.
1726 // because we're dealing with a mesh, we dont have to deal with anything
1727 // "down-route" from this server (nice huh)
1729 char reason[MAXBUF];
1733 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1735 if (strcasecmp(u->second->server,ServerName))
1737 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1738 kill_link(u->second,reason);
1748 void force_nickchange(userrec* user,const char* newnick)
1755 FOREACH_RESULT(OnUserPreNick(user,newnick));
1758 kill_link(user,"Nickname collision");
1761 if (matches_qline(newnick))
1764 kill_link(user,"Nickname collision");
1772 strncpy(nick,newnick,MAXBUF);
1774 if (user->registered == 7)
1778 handle_nick(pars,1,user);
1784 int process_parameters(char **command_p,char *parameters)
1787 int q = strlen(parameters);
1790 /* no parameters, command_p invalid! */
1793 if (parameters[0] == ':')
1795 command_p[0] = parameters+1;
1800 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1802 /* only one parameter */
1803 command_p[0] = parameters;
1804 if (parameters[0] == ':')
1806 if (strchr(parameters,' ') != NULL)
1814 command_p[j++] = parameters;
1815 for (int i = 0; i <= q; i++)
1817 if (parameters[i] == ' ')
1819 command_p[j++] = parameters+i+1;
1820 parameters[i] = '\0';
1821 if (command_p[j-1][0] == ':')
1823 *command_p[j-1]++; /* remove dodgy ":" */
1825 /* parameter like this marks end of the sequence */
1829 return j; /* returns total number of items in the list */
1832 void process_command(userrec *user, char* cmd)
1836 char *command_p[127];
1837 char p[MAXBUF], temp[MAXBUF];
1838 int j, items, cmd_found;
1840 for (int i = 0; i < 127; i++)
1841 command_p[i] = NULL;
1856 int total_params = 0;
1859 for (int q = 0; q < strlen(cmd)-1; q++)
1861 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1864 // found a 'trailing', we dont count them after this.
1872 // another phidjit bug...
1873 if (total_params > 126)
1875 *(strchr(cmd,' ')) = '\0';
1876 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1880 strlcpy(temp,cmd,MAXBUF);
1882 std::string tmp = cmd;
1883 for (int i = 0; i <= MODCOUNT; i++)
1885 std::string oldtmp = tmp;
1886 modules[i]->OnServerRaw(tmp,true,user);
1889 log(DEBUG,"A Module changed the input string!");
1890 log(DEBUG,"New string: %s",tmp.c_str());
1891 log(DEBUG,"Old string: %s",oldtmp.c_str());
1895 strlcpy(cmd,tmp.c_str(),MAXBUF);
1896 strlcpy(temp,cmd,MAXBUF);
1898 if (!strchr(cmd,' '))
1900 /* no parameters, lets skip the formalities and not chop up
1902 log(DEBUG,"About to preprocess command with no params");
1904 command_p[0] = NULL;
1906 for (int i = 0; i <= strlen(cmd); i++)
1908 cmd[i] = toupper(cmd[i]);
1916 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1917 for (int i = 0; i < strlen(temp); i++)
1919 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1925 /* split the full string into a command plus parameters */
1929 if (strchr(cmd,' '))
1931 for (int i = 0; i <= strlen(cmd); i++)
1933 /* capitalise the command ONLY, leave params intact */
1934 cmd[i] = toupper(cmd[i]);
1935 /* are we nearly there yet?! :P */
1939 parameters = cmd+i+1;
1947 for (int i = 0; i <= strlen(cmd); i++)
1949 cmd[i] = toupper(cmd[i]);
1956 if (strlen(command)>MAXCOMMAND)
1958 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1962 for (int x = 0; x < strlen(command); x++)
1964 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1966 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1968 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1971 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1978 for (int i = 0; i != cmdlist.size(); i++)
1980 if (cmdlist[i].command[0])
1982 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1988 items = process_parameters(command_p,parameters);
1993 command_p[0] = NULL;
1999 command_p[0] = NULL;
2004 /* activity resets the ping pending timer */
2005 user->nping = TIME + user->pingmax;
2006 if ((items) < cmdlist[i].min_params)
2008 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2009 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2012 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2014 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2015 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2019 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2021 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2022 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2026 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2028 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2030 if ((!isnick(user->nick)) || (user->registered != 7))
2032 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2033 WriteServ(user->fd,"451 %s :You have not registered",command);
2037 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2041 mycmd = strtok_r(DisabledCommands," ",&savept2);
2044 if (!strcasecmp(mycmd,command))
2046 // command is disabled!
2047 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2050 mycmd = strtok_r(NULL," ",&savept2);
2055 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2057 if (cmdlist[i].handler_function)
2060 /* ikky /stats counters */
2063 cmdlist[i].use_count++;
2064 cmdlist[i].total_bytes+=strlen(temp);
2068 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2069 if (MOD_RESULT == 1) {
2073 /* WARNING: nothing may come after the
2074 * command handler call, as the handler
2075 * may free the user structure! */
2077 cmdlist[i].handler_function(command_p,items,user);
2083 WriteServ(user->fd,"451 %s :You have not registered",command);
2091 if ((!cmd_found) && (user))
2094 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2098 bool removecommands(const char* source)
2100 bool go_again = true;
2104 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2106 if (!strcmp(i->source,source))
2108 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2119 void process_buffer(const char* cmdbuf,userrec *user)
2123 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2129 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2136 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2138 strlcpy(cmd,cmdbuf,MAXBUF);
2143 int sl = strlen(cmd)-1;
2144 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2149 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2154 while (cmd[sl] == ' ') // strip trailing spaces
2164 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2166 if ((user) && (cmd))
2168 process_command(user,cmd);
2172 void DoSync(serverrec* serv, char* tcp_host)
2175 log(DEBUG,"Sending sync");
2176 // send start of sync marker: Y <timestamp>
2177 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2178 // except the ones its receiving it from.
2179 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2180 serv->SendPacket(data,tcp_host);
2181 // send users and channels
2183 NetSendMyRoutingTable();
2185 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2186 for (int j = 0; j < 32; j++)
2190 for (int k = 0; k < me[j]->connectors.size(); k++)
2192 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2194 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2195 serv->SendPacket(data,tcp_host);
2201 // send our version for the remote side to cache
2202 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2203 serv->SendPacket(data,tcp_host);
2205 // sync the users and channels, give the modules a look-in.
2206 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2208 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);
2209 serv->SendPacket(data,tcp_host);
2210 if (strchr(u->second->modes,'o'))
2212 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2213 serv->SendPacket(data,tcp_host);
2215 for (int i = 0; i <= MODCOUNT; i++)
2217 string_list l = modules[i]->OnUserSync(u->second);
2218 for (int j = 0; j < l.size(); j++)
2220 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2221 serv->SendPacket(data,tcp_host);
2224 char* chl = chlist(u->second,u->second);
2227 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2228 serv->SendPacket(data,tcp_host);
2231 // send channel modes, topics etc...
2232 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2234 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2235 serv->SendPacket(data,tcp_host);
2236 for (int i = 0; i <= MODCOUNT; i++)
2238 string_list l = modules[i]->OnChannelSync(c->second);
2239 for (int j = 0; j < l.size(); j++)
2241 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2242 serv->SendPacket(data,tcp_host);
2245 if (c->second->topic[0])
2247 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);
2248 serv->SendPacket(data,tcp_host);
2250 // send current banlist
2252 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2254 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2255 serv->SendPacket(data,tcp_host);
2258 // sync global zlines, glines, etc
2259 sync_xlines(serv,tcp_host);
2261 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2262 serv->SendPacket(data,tcp_host);
2263 log(DEBUG,"Sent sync");
2264 // ircd sends its serverlist after the end of sync here
2268 void NetSendMyRoutingTable()
2270 // send out a line saying what is reachable to us.
2271 // E.g. if A is linked to B C and D, send out:
2273 // if its only linked to B and D send out:
2275 // if it has no links, dont even send out the line at all.
2276 char buffer[MAXBUF];
2277 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2278 bool sendit = false;
2279 for (int i = 0; i < 32; i++)
2283 for (int j = 0; j < me[i]->connectors.size(); j++)
2285 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2287 strlcat(buffer," ",MAXBUF);
2288 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2295 NetSendToAll(buffer);
2299 void DoSplit(const char* params)
2301 bool go_again = true;
2305 for (int i = 0; i < 32; i++)
2309 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2311 if (!strcasecmp(j->GetServerName().c_str(),params))
2314 j->CloseConnection();
2315 me[i]->connectors.erase(j);
2323 log(DEBUG,"Removed server. Will remove clients...");
2324 // iterate through the userlist and remove all users on this server.
2325 // because we're dealing with a mesh, we dont have to deal with anything
2326 // "down-route" from this server (nice huh)
2328 char reason[MAXBUF];
2329 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2333 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2335 if (!strcasecmp(u->second->server,params))
2337 kill_link(u->second,reason);
2345 // removes a server. Will NOT remove its users!
2347 void RemoveServer(const char* name)
2349 bool go_again = true;
2353 for (int i = 0; i < 32; i++)
2357 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2359 if (!strcasecmp(j->GetServerName().c_str(),name))
2362 j->CloseConnection();
2363 me[i]->connectors.erase(j);
2374 char MODERR[MAXBUF];
2381 void erase_factory(int j)
2384 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2389 factory.push_back(NULL);
2396 void erase_module(int j)
2399 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2405 modules.push_back(NULL);
2411 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2415 module_names.erase(v);
2423 bool UnloadModule(const char* filename)
2425 std::string filename_str = filename;
2426 for (int j = 0; j != module_names.size(); j++)
2428 if (module_names[j] == filename_str)
2430 if (modules[j]->GetVersion().Flags & VF_STATIC)
2432 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2433 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2437 log(DEBUG,"Deleting module...");
2439 log(DEBUG,"Erasing module entry...");
2441 log(DEBUG,"Removing dependent commands...");
2442 removecommands(filename);
2443 log(DEFAULT,"Module %s unloaded",filename);
2448 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2449 snprintf(MODERR,MAXBUF,"Module not loaded");
2453 bool LoadModule(const char* filename)
2455 char modfile[MAXBUF];
2457 snprintf(modfile,MAXBUF,"%s",filename);
2459 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2461 std::string filename_str = filename;
2463 if (!DirValid(modfile))
2465 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2466 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2470 log(DEBUG,"Loading module: %s",modfile);
2472 if (FileExists(modfile))
2475 for (int j = 0; j < module_names.size(); j++)
2477 if (module_names[j] == filename_str)
2479 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2480 snprintf(MODERR,MAXBUF,"Module already loaded");
2484 ircd_module* a = new ircd_module(modfile);
2485 factory[MODCOUNT+1] = a;
2486 if (factory[MODCOUNT+1]->LastError())
2488 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2489 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2493 if (factory[MODCOUNT+1]->factory)
2495 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2496 modules[MODCOUNT+1] = m;
2497 /* save the module and the module's classfactory, if
2498 * this isnt done, random crashes can occur :/ */
2499 module_names.push_back(filename);
2503 log(DEFAULT,"Unable to load %s",modfile);
2504 snprintf(MODERR,MAXBUF,"Factory function failed!");
2511 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2512 snprintf(MODERR,MAXBUF,"Module file could not be found");
2521 bool GotServer(std::string name)
2523 for (int j = 0; j < 32; j++)
2527 for (int k = 0; k < me[j]->connectors.size(); k++)
2529 if (name == me[j]->connectors[k].GetServerName())
2540 int InspIRCd(char** argv, int argc)
2542 struct sockaddr_in client,server;
2543 char addrs[MAXBUF][255];
2544 int incomingSockfd, result = TRUE;
2547 int selectResult = 0, selectResult2 = 0;
2548 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2552 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2553 log_file = fopen(logpath.c_str(),"a+");
2556 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2561 printf("Logging to ircd.log...\n");
2563 printf("Logging to %s...\n",logpath.c_str());
2566 log(DEFAULT,"$Id$");
2569 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2571 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2573 SetupCommandTable();
2574 log(DEBUG,"InspIRCd: startup: default command table set up");
2576 ReadConfig(true,NULL);
2579 printf("WARNING: %s\n\n",DieValue);
2580 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2583 log(DEBUG,"InspIRCd: startup: read config");
2585 int clientportcount = 0, serverportcount = 0;
2587 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2589 ConfValue("bind","port",count,configToken,&config_f);
2590 ConfValue("bind","address",count,Addr,&config_f);
2591 ConfValue("bind","type",count,Type,&config_f);
2592 if (!strcmp(Type,"servers"))
2594 char Default[MAXBUF];
2595 strcpy(Default,"no");
2596 ConfValue("bind","default",count,Default,&config_f);
2597 if (strchr(Default,'y'))
2599 defaultRoute = serverportcount;
2600 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2602 me[serverportcount] = new serverrec(ServerName,100L,false);
2603 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2605 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2606 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2615 ports[clientportcount] = atoi(configToken);
2616 strlcpy(addrs[clientportcount],Addr,256);
2619 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2621 portCount = clientportcount;
2622 SERVERportCount = serverportcount;
2624 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2625 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2629 /* BugFix By Craig! :p */
2631 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2633 ConfValue("module","name",count,configToken,&config_f);
2634 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2635 if (!LoadModule(configToken))
2637 log(DEFAULT,"Exiting due to a module loader error.");
2638 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2642 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2644 startup_time = time(NULL);
2647 ConfValue("pid","file",0,PID,&config_f);
2648 // write once here, to try it out and make sure its ok
2651 /* setup select call */
2653 FD_ZERO(&selectFds);
2655 log(DEBUG,"InspIRCd: startup: zero selects");
2656 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2658 for (count = 0; count < portCount; count++)
2660 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2662 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2665 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2667 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2669 else /* well we at least bound to one socket so we'll continue */
2675 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2677 /* if we didn't bind to anything then abort */
2678 if (boundPortCount == 0)
2680 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2681 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2686 printf("\nInspIRCd is now running!\n");
2690 log(VERBOSE,"Not forking as -nofork was specified");
2694 if (DaemonSeed() == ERROR)
2696 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2697 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2702 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2707 if ((kq == -1) || (lkq == -1) || (skq == -1))
2709 log(DEFAULT,"main: kqueue() failed!");
2710 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2716 ep = epoll_create(MAXCLIENTS);
2717 lep = epoll_create(32);
2718 sep = epoll_create(128);
2719 if ((ep == -1) || (lep == -1) || (sep == -1))
2721 log(DEFAULT,"main: epoll_create() failed!");
2722 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2728 log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2729 for (count = 0; count < boundPortCount; count++)
2731 struct epoll_event ev;
2732 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2733 ev.events = EPOLLIN | EPOLLET;
2734 ev.data.fd = openSockfd[count];
2735 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2738 log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2739 printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2744 for (int t = 0; t != SERVERportCount; t++)
2746 struct epoll_event ev;
2747 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2748 ev.events = EPOLLIN | EPOLLET;
2749 ev.data.fd = me[t]->fd;
2750 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2753 log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2754 printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2760 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2761 for (count = 0; count < boundPortCount; count++)
2764 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2765 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2766 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2769 log(DEFAULT,"main: add listen ports to kqueue failed!");
2770 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2774 for (int t = 0; t != SERVERportCount; t++)
2779 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2780 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2781 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2784 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2785 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2793 log(DEFAULT,"Using standard select socket engine.");
2799 length = sizeof (client);
2800 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2804 struct kevent ke_list[33];
2808 struct epoll_event event[33];
2812 tvs.tv_usec = 10000L;
2815 tv.tv_usec = 10000L;
2819 tval.tv_usec = 10000L;
2821 int total_in_this_set = 0;
2822 int i = 0, v = 0, j = 0, cycle_iter = 0;
2823 bool expire_run = false;
2825 /* main loop, this never returns */
2828 #ifdef _POSIX_PRIORITY_SCHEDULING
2834 // we only read time() once per iteration rather than tons of times!
2840 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2841 // them in a list, then reap the list every second or so.
2842 if (((TIME % 5) == 0) && (!expire_run))
2844 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2846 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2847 ConfValue("link","name",i,Link_ServerName,&config_f);
2848 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2849 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2851 autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2852 if (a != autoconns.end())
2854 if (TIME > a->second)
2856 ConnectServer(Link_ServerName,NULL);
2857 a->second = TIME + atoi(Link_AConn);
2864 FOREACH_MOD OnBackgroundTimer(TIME);
2868 if ((TIME % 5) == 1)
2871 // fix by brain - this must be below any manipulation of the hashmap by modules
2872 user_hash::iterator count2 = clientlist.begin();
2875 i = epoll_wait(sep, event, 1, EP_DELAY);
2878 log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2879 for (int x = 0; x != SERVERportCount; x++)
2881 if ((me[x]) && (event[0].data.fd == me[x]->fd))
2886 ts.tv_nsec = 30000L;
2887 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2890 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2891 for (int x = 0; x != SERVERportCount; x++)
2893 if ((me[x]) && (ke.ident == me[x]->fd))
2898 FD_ZERO(&serverfds);
2899 for (int x = 0; x != SERVERportCount; x++)
2902 FD_SET(me[x]->fd, &serverfds);
2904 tvs.tv_usec = 30000L;
2906 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2909 for (int x = 0; x != SERVERportCount; x++)
2911 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2914 char remotehost[MAXBUF],resolved[MAXBUF];
2915 length = sizeof (client);
2916 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2917 if (incomingSockfd != -1)
2919 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2920 if(CleanAndResolve(resolved, remotehost) != TRUE)
2922 strlcpy(resolved,remotehost,MAXBUF);
2924 // add to this connections ircd_connector vector
2925 // *FIX* - we need the LOCAL port not the remote port in &client!
2926 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2932 std::deque<std::string> msgs;
2933 std::deque<std::string> sums;
2934 for (int x = 0; x < SERVERportCount; x++)
2937 me[x]->FlushWriteBuffers();
2940 while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2942 for (int ctr = 0; ctr < msgs.size(); ctr++)
2944 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2945 strlcpy(tcp_sum,msgs[ctr].c_str(),MAXBUF);
2946 log(DEBUG,"Processing: %s",tcp_msg);
2949 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2952 // during a netburst, send all data to all other linked servers
2953 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2955 if (is_uline(tcp_host))
2957 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2959 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2963 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2965 std::string msg = tcp_msg;
2966 FOREACH_MOD OnPacketReceive(msg,tcp_host);
2967 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2969 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2970 if (!me[x]->FindHost(tcp_host))
2972 log(DEBUG,"Connector gone, bailing!");
2976 sums.clear(); // we're done, clear the list for the next operation
2981 while (count2 != clientlist.end())
2987 total_in_this_set = 0;
2989 user_hash::iterator xcount = count2;
2990 user_hash::iterator endingiter = count2;
2992 if (count2 == clientlist.end()) break;
2994 userrec* curr = NULL;
2997 curr = count2->second;
2999 if ((long)curr == -1)
3002 if ((curr) && (curr->fd != 0))
3004 #ifdef _POSIX_PRIORITY_SCHEDULING
3007 // assemble up to 64 sockets into an fd_set
3008 // to implement a pooling mechanism.
3010 // This should be up to 64x faster than the
3011 // old implementation.
3013 while (total_in_this_set < 1024)
3015 if (count2 != clientlist.end())
3017 curr = count2->second;
3018 if ((long)curr == -1)
3020 int currfd = curr->fd;
3021 // we don't check the state of remote users.
3022 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3024 curr->FlushWriteBuf();
3025 if (curr->GetWriteError() != "")
3027 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3028 kill_link(curr,curr->GetWriteError().c_str());
3032 FD_SET (curr->fd, &sfd);
3034 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3035 // their connection class.
3036 if ((TIME > curr->timeout) && (curr->registered != 7))
3038 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3039 kill_link(curr,"Registration timeout");
3042 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3044 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3045 curr->dns_done = true;
3047 FullConnectUser(curr);
3048 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3051 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3053 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3054 FullConnectUser(curr);
3055 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3058 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3060 if ((!curr->lastping) && (curr->registered == 7))
3062 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3063 kill_link(curr,"Ping timeout");
3066 Write(curr->fd,"PING :%s",ServerName);
3067 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3069 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3073 total_in_this_set++;
3077 endingiter = count2;
3078 count2 = xcount; // roll back to where we were
3080 // 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.
3081 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3083 if (cycle_iter > 20) while (count2 != clientlist.end())
3086 if (count2 != clientlist.end())
3088 curr = count2->second;
3089 if ((long)curr == -1)
3091 int currfd = curr->fd;
3092 // we don't check the state of remote users.
3093 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3096 curr->FlushWriteBuf();
3097 if (curr->GetWriteError() != "")
3099 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3100 kill_link(curr,curr->GetWriteError().c_str());
3104 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3105 // their connection class.
3106 if ((TIME > curr->timeout) && (curr->registered != 7))
3108 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3109 kill_link(curr,"Registration timeout");
3113 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3115 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3116 curr->dns_done = true;
3118 FullConnectUser(curr);
3119 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3122 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3124 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3125 FullConnectUser(curr);
3126 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3129 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3131 if ((!curr->lastping) && (curr->registered == 7))
3133 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3134 kill_link(curr,"Ping timeout");
3137 Write(curr->fd,"PING :%s",ServerName);
3138 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3140 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3147 // increment the counter right to the end of the list, as kqueue processes everything in one go
3152 int i = epoll_wait(ep, event, 1, 5);
3155 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3156 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3157 userrec* cu = fd_ref_table[event[0].data.fd];
3162 // for now, we only read 1 event. We could read soooo many more :)
3163 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3166 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3167 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3168 userrec* cu = fd_ref_table[ke.ident];
3172 tval.tv_usec = 1000L;
3173 selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3174 // now loop through all of the items in this pool if any are waiting
3175 if ((selectResult2 > 0) && (xcount != clientlist.end()))
3176 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3178 // SELECT: we have to iterate...
3179 if (count2a == clientlist.end())
3181 userrec* cu = count2a->second;
3184 #ifdef _POSIX_PRIORITY_SCHEDULING
3189 // EPOLL: We already know we have a valid FD. No checks needed.
3190 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3193 // KQUEUE: We already know we have a valid FD. No checks needed.
3194 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3197 // SELECT: We don't know if our FD is valid.
3198 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3201 log(DEBUG,"Data waiting on socket %d",cu->fd);
3204 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3207 result = cu->ReadData(data, 65535);
3209 else result = result2;
3210 log(DEBUG,"Read result: %d",result);
3213 statsRecv += result;
3214 // perform a check on the raw buffer as an array (not a string!) to remove
3215 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3216 // hopefully this should stop even more people whining about "Unknown command: *"
3217 for (int checker = 0; checker < result; checker++)
3219 if ((data[checker] == 0) || (data[checker] == 7))
3220 data[checker] = ' ';
3223 data[result] = '\0';
3224 userrec* current = cu;
3225 int currfd = current->fd;
3227 // add the data to the users buffer
3229 if (!current->AddBuffer(data))
3231 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3232 if (current->registered == 7)
3234 kill_link(current,"RecvQ exceeded");
3238 WriteOpers("*** Excess flood from %s",current->ip);
3239 log(DEFAULT,"Excess flood from: %s",current->ip);
3240 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3245 if (current->recvq.length() > NetBufferSize)
3247 if (current->registered == 7)
3249 kill_link(current,"RecvQ exceeded");
3253 WriteOpers("*** Excess flood from %s",current->ip);
3254 log(DEFAULT,"Excess flood from: %s",current->ip);
3255 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3260 // while there are complete lines to process...
3261 while (current->BufferIsReady())
3264 if (TIME > current->reset_due)
3266 current->reset_due = TIME + current->threshold;
3267 current->lines_in = 0;
3269 current->lines_in++;
3270 if (current->lines_in > current->flood)
3272 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3273 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3274 kill_link(current,"Excess flood");
3277 if ((floodlines > current->flood) && (current->flood != 0))
3279 if (current->registered == 7)
3281 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3282 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3283 kill_link(current,"Excess flood");
3287 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3292 char sanitized[MAXBUF];
3293 // use GetBuffer to copy single lines into the sanitized string
3294 std::string single_line = current->GetBuffer();
3295 current->bytes_in += single_line.length();
3297 if (single_line.length()>512)
3299 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3300 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3301 kill_link(current,"Excess flood");
3304 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3307 userrec* old_comp = fd_ref_table[currfd];
3308 // we're gonna re-scan to check if the nick is gone, after every
3309 // command - if it has, we're gonna bail
3310 process_buffer(sanitized,current);
3311 // look for the user's record in case it's changed... if theyve quit,
3312 // we cant do anything more with their buffer, so bail.
3313 // there used to be an ugly, slow loop here. Now we have a reference
3314 // table, life is much easier (and FASTER)
3315 userrec* new_comp = fd_ref_table[currfd];
3316 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3324 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3326 log(DEBUG,"killing: %s",cu->nick);
3327 kill_link(cu,strerror(errno));
3331 // result EAGAIN means nothing read
3332 if (result == EAGAIN)
3342 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3343 kill_link(cu,"Client exited");
3344 // must bail here? kill_link removes the hash, corrupting the iterator
3345 log(DEBUG,"Bailing from client exit");
3351 else if (result > 0)
3356 for (int q = 0; q < total_in_this_set; q++)
3362 #ifdef _POSIX_PRIORITY_SCHEDULING
3367 // set up select call
3368 for (count = 0; count < boundPortCount; count++)
3370 FD_SET (openSockfd[count], &selectFds);
3373 tv.tv_usec = 30000L;
3374 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3376 /* select is reporting a waiting socket. Poll them all to find out which */
3377 if (selectResult > 0)
3379 for (count = 0; count < boundPortCount; count++)
3381 if (FD_ISSET (openSockfd[count], &selectFds))
3386 ts.tv_nsec = 30000L;
3387 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3388 if (i > 0) for (j = 0; j < i; j++)
3390 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3391 // this isnt as efficient as it could be, we could create a reference table
3392 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3393 // number of listening ports on the average ircd is a small number (less than 20)
3394 // compared to the number of clients (possibly over 2000)
3395 for (count = 0; count < boundPortCount; count++)
3397 if (ke_list[j].ident == openSockfd[count])
3401 i = epoll_wait(lep, event, 32, EP_DELAY);
3402 if (i > 0) for (j = 0; j < i; j++)
3404 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3405 for (count = 0; count < boundPortCount; count++)
3407 if (event[j].data.fd == openSockfd[count])
3410 char target[MAXBUF], resolved[MAXBUF];
3411 length = sizeof (client);
3412 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3414 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3415 strlcpy (resolved, target, MAXBUF);
3417 if (incomingSockfd < 0)
3419 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3420 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3425 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3427 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3428 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3435 #ifdef _POSIX_PRIORITY_SCHEDULING
3441 close (incomingSockfd);