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...");
405 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
407 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
408 ConfValue("link","name",i,Link_ServerName,&config_f);
409 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
410 if (strcmp(Link_AConn,""))
412 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
417 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
420 log(DEFAULT,"Adding and removing modules due to rehash...");
422 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
424 // store the old module names
425 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
427 old_module_names.push_back(*t);
430 // get the new module names
431 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
433 ConfValue("module","name",count2,Value,&config_f);
434 new_module_names.push_back(Value);
437 // now create a list of new modules that are due to be loaded
438 // and a seperate list of modules which are due to be unloaded
439 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
442 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
448 added_modules.push_back(*_new);
450 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
453 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
459 removed_modules.push_back(*oldm);
461 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
463 int rem = 0, add = 0;
464 if (!removed_modules.empty())
465 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
467 if (UnloadModule(removing->c_str()))
469 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
470 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
475 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
478 if (!added_modules.empty())
479 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
481 if (LoadModule(adding->c_str()))
483 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
484 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
489 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
492 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());
497 /* add a channel to a user, creating the record for it if needed and linking
498 * it to the user record */
500 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
502 if ((!user) || (!cn))
504 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
512 strncpy(cname,cn,MAXBUF);
514 // we MUST declare this wherever we use FOREACH_RESULT
517 if (strlen(cname) > CHANMAX-1)
519 cname[CHANMAX-1] = '\0';
522 log(DEBUG,"add_channel: %s %s",user->nick,cname);
524 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
526 return NULL; // already on the channel!
530 if (!FindChan(cname))
533 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
534 if (MOD_RESULT == 1) {
538 /* create a new one */
539 log(DEBUG,"add_channel: creating: %s",cname);
541 chanlist[cname] = new chanrec();
543 strlcpy(chanlist[cname]->name, cname,CHANMAX);
544 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
545 chanlist[cname]->created = TIME;
546 strcpy(chanlist[cname]->topic, "");
547 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
548 chanlist[cname]->topicset = 0;
549 Ptr = chanlist[cname];
550 log(DEBUG,"add_channel: created: %s",cname);
551 /* set created to 2 to indicate user
552 * is the first in the channel
553 * and should be given ops */
559 /* channel exists, just fish out a pointer to its struct */
560 Ptr = FindChan(cname);
563 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
565 // the override flag allows us to bypass channel modes
566 // and bans (used by servers)
567 if ((!override) || (!strcasecmp(user->server,ServerName)))
569 log(DEBUG,"Not overriding...");
571 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
572 if (MOD_RESULT == 1) {
575 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
579 log(DEBUG,"add_channel: checking key, invite, etc");
581 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
586 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
589 log(DEBUG,"add_channel: no key given in JOIN");
590 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
595 if (strcasecmp(key,Ptr->key))
597 log(DEBUG,"add_channel: bad key given in JOIN");
598 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
603 log(DEBUG,"add_channel: no key");
606 FOREACH_RESULT(OnCheckInvite(user, Ptr));
609 if (Ptr->binarymodes & CM_INVITEONLY)
611 log(DEBUG,"add_channel: channel is +i");
612 if (user->IsInvited(Ptr->name))
614 /* user was invited to channel */
615 /* there may be an optional channel NOTICE here */
619 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
623 log(DEBUG,"add_channel: channel is not +i");
626 FOREACH_RESULT(OnCheckLimit(user, Ptr));
631 if (usercount(Ptr) >= Ptr->limit)
633 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
638 log(DEBUG,"add_channel: about to walk banlist");
640 FOREACH_RESULT(OnCheckBan(user, Ptr));
643 /* check user against the channel banlist */
646 if (Ptr->bans.size())
648 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
650 if (match(user->GetFullHost(),i->data))
652 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
658 log(DEBUG,"add_channel: bans checked");
666 user->RemoveInvite(Ptr->name);
669 log(DEBUG,"add_channel: invites removed");
674 log(DEBUG,"Overridden checks");
682 log(DEBUG,"Passed channel checks");
684 for (int index =0; index != MAXCHANS; index++)
686 log(DEBUG,"Check location %d",index);
687 if (user->chans[index].channel == NULL)
689 log(DEBUG,"Adding into their channel list at location %d",index);
693 /* first user in is given ops */
694 user->chans[index].uc_modes = UCMODE_OP;
698 user->chans[index].uc_modes = 0;
700 user->chans[index].channel = Ptr;
701 Ptr->AddUser((char*)user);
702 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
704 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
706 // use the stamdard J token with no privilages.
710 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
714 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
716 NetSendToAll(buffer);
719 log(DEBUG,"Sent JOIN to client");
723 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
724 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
727 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
728 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
729 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
730 FOREACH_MOD OnUserJoin(user,Ptr);
734 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
735 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
739 /* remove a channel from a users record, and remove the record from memory
740 * if the channel has become empty */
742 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
744 if ((!user) || (!cname))
746 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
752 if ((!cname) || (!user))
757 Ptr = FindChan(cname);
764 FOREACH_MOD OnUserPart(user,Ptr);
765 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
767 for (int i =0; i != MAXCHANS; i++)
769 /* zap it from the channel list of the user */
770 if (user->chans[i].channel == Ptr)
774 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
779 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
780 NetSendToAll(buffer);
790 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
791 NetSendToAll(buffer);
794 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
796 user->chans[i].uc_modes = 0;
797 user->chans[i].channel = NULL;
798 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
803 Ptr->DelUser((char*)user);
805 /* if there are no users left on the channel */
808 chan_hash::iterator iter = chanlist.find(Ptr->name);
810 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
812 /* kill the record */
813 if (iter != chanlist.end())
815 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
817 chanlist.erase(iter);
823 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
825 if ((!src) || (!user) || (!Ptr) || (!reason))
827 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
831 if ((!Ptr) || (!user) || (!src))
836 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
838 if (!has_channel(user,Ptr))
840 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
845 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
846 if (MOD_RESULT == ACR_DENY)
849 if (MOD_RESULT == ACR_DEFAULT)
851 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
853 if (cstatus(src,Ptr) == STATUS_HOP)
855 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
859 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
867 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
871 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
873 for (int i =0; i != MAXCHANS; i++)
875 /* zap it from the channel list of the user */
876 if (user->chans[i].channel)
877 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
879 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
880 user->chans[i].uc_modes = 0;
881 user->chans[i].channel = NULL;
882 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
887 Ptr->DelUser((char*)user);
889 /* if there are no users left on the channel */
892 chan_hash::iterator iter = chanlist.find(Ptr->name);
894 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
896 /* kill the record */
897 if (iter != chanlist.end())
899 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
901 chanlist.erase(iter);
909 /* This function pokes and hacks at a parameter list like the following:
911 * PART #winbot,#darkgalaxy :m00!
913 * to turn it into a series of individual calls like this:
916 * PART #darkgalaxy :m00!
918 * The seperate calls are sent to a callback function provided by the caller
919 * (the caller will usually call itself recursively). The callback function
920 * must be a command handler. Calling this function on a line with no list causes
921 * no action to be taken. You must provide a starting and ending parameter number
922 * where the range of the list can be found, useful if you have a terminating
923 * parameter as above which is actually not part of the list, or parameters
924 * before the actual list as well. This code is used by many functions which
925 * can function as "one to list" (see the RFC) */
927 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
932 char blog[32][MAXBUF];
933 char blog2[32][MAXBUF];
934 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
938 for (int i = 0; i <32; i++)
941 for (int i = 0; i <32; i++)
945 for (int i = 0; i <10; i++)
954 if (pcnt > 1) /* we have a key to copy */
956 strlcpy(keystr,parameters[1],MAXBUF);
960 if (!parameters[start])
964 if (!strchr(parameters[start],','))
969 for (int i = start; i <= end; i++)
973 strlcat(plist,parameters[i],MAXBUF);
981 for (int i = 0; i < t; i++)
986 strlcpy(blog[j++],param,MAXBUF);
990 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
995 strlcpy(blog[j++],param,MAXBUF);
998 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1003 if ((joins) && (keystr))
1005 if (strchr(keystr,','))
1009 t2 = strlen(keystr);
1010 for (int i = 0; i < t2; i++)
1012 if (keystr[i] == ',')
1015 strlcpy(blog2[j++],param,MAXBUF);
1019 strlcpy(blog2[j++],param,MAXBUF);
1024 for (j = 0; j < total; j++)
1030 for (q = end; q < pcnt-1; q++)
1032 if (parameters[q+1])
1034 pars[q-end+1] = parameters[q+1];
1037 if ((joins) && (parameters[1]))
1048 /* repeatedly call the function with the hacked parameter list */
1049 if ((joins) && (pcnt > 1))
1053 // pars[1] already set up and containing key from blog2[j]
1058 pars[1] = parameters[1];
1064 fn(pars,pcnt-(end-start),u);
1073 void kill_link(userrec *user,const char* r)
1075 user_hash::iterator iter = clientlist.find(user->nick);
1077 char reason[MAXBUF];
1079 strncpy(reason,r,MAXBUF);
1081 if (strlen(reason)>MAXQUIT)
1083 reason[MAXQUIT-1] = '\0';
1086 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1087 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1088 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1090 if (user->registered == 7) {
1091 FOREACH_MOD OnUserQuit(user);
1092 WriteCommonExcept(user,"QUIT :%s",reason);
1094 // Q token must go to ALL servers!!!
1095 char buffer[MAXBUF];
1096 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1097 NetSendToAll(buffer);
1100 user->FlushWriteBuf();
1102 FOREACH_MOD OnUserDisconnect(user);
1106 FOREACH_MOD OnRawSocketClose(user->fd);
1109 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1110 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1113 log(DEBUG,"kqueue: Failed to remove user from queue!");
1117 struct epoll_event ev;
1118 ev.events = EPOLLIN | EPOLLET;
1119 ev.data.fd = user->fd;
1120 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1123 log(DEBUG,"epoll: List deletion failure!");
1126 user->CloseSocket();
1129 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1130 // if they were an oper with +s.
1131 if (user->registered == 7) {
1132 purge_empty_chans(user);
1133 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1137 if (iter != clientlist.end())
1139 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1141 fd_ref_table[user->fd] = NULL;
1142 clientlist.erase(iter);
1147 void kill_link_silent(userrec *user,const char* r)
1149 user_hash::iterator iter = clientlist.find(user->nick);
1151 char reason[MAXBUF];
1153 strncpy(reason,r,MAXBUF);
1155 if (strlen(reason)>MAXQUIT)
1157 reason[MAXQUIT-1] = '\0';
1160 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1161 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1162 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1164 user->FlushWriteBuf();
1166 if (user->registered == 7) {
1167 FOREACH_MOD OnUserQuit(user);
1168 WriteCommonExcept(user,"QUIT :%s",reason);
1170 // Q token must go to ALL servers!!!
1171 char buffer[MAXBUF];
1172 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1173 NetSendToAll(buffer);
1176 FOREACH_MOD OnUserDisconnect(user);
1180 FOREACH_MOD OnRawSocketClose(user->fd);
1183 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1184 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1187 log(DEBUG,"kqueue: Failed to remove user from queue!");
1191 struct epoll_event ev;
1192 ev.events = EPOLLIN | EPOLLET;
1193 ev.data.fd = user->fd;
1194 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1197 log(DEBUG,"epoll: List deletion failure!");
1200 user->CloseSocket();
1203 if (user->registered == 7) {
1204 purge_empty_chans(user);
1207 if (iter != clientlist.end())
1209 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1211 fd_ref_table[user->fd] = NULL;
1212 clientlist.erase(iter);
1218 int main(int argc, char** argv)
1222 log(DEBUG,"*** InspIRCd starting up!");
1223 if (!FileExists(CONFIG_FILE))
1225 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1226 log(DEFAULT,"main: no config");
1227 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1231 for (int i = 1; i < argc; i++)
1233 if (!strcmp(argv[i],"-nofork")) {
1236 if (!strcmp(argv[i],"-wait")) {
1239 if (!strcmp(argv[i],"-nolimit")) {
1244 strlcpy(MyExecutable,argv[0],MAXBUF);
1246 // initialize the lowercase mapping table
1247 for (int cn = 0; cn < 256; cn++)
1249 // lowercase the uppercase chars
1250 for (int cn = 65; cn < 91; cn++)
1251 lowermap[cn] = tolower(cn);
1252 // now replace the specific chars for scandanavian comparison
1253 lowermap['['] = '{';
1254 lowermap[']'] = '}';
1255 lowermap['\\'] = '|';
1257 if (InspIRCd(argv,argc) == ERROR)
1259 log(DEFAULT,"main: daemon function bailed");
1260 printf("ERROR: could not initialise. Shutting down.\n");
1267 template<typename T> inline string ConvToStr(const T &in)
1270 if (!(tmp << in)) return string();
1274 /* re-allocates a nick in the user_hash after they change nicknames,
1275 * returns a pointer to the new user as it may have moved */
1277 userrec* ReHashNick(char* Old, char* New)
1279 //user_hash::iterator newnick;
1280 user_hash::iterator oldnick = clientlist.find(Old);
1282 log(DEBUG,"ReHashNick: %s %s",Old,New);
1284 if (!strcasecmp(Old,New))
1286 log(DEBUG,"old nick is new nick, skipping");
1287 return oldnick->second;
1290 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1292 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1294 userrec* olduser = oldnick->second;
1295 clientlist[New] = olduser;
1296 clientlist.erase(oldnick);
1298 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1300 return clientlist[New];
1303 /* adds or updates an entry in the whowas list */
1304 void AddWhoWas(userrec* u)
1306 whowas_hash::iterator iter = whowas.find(u->nick);
1307 WhoWasUser *a = new WhoWasUser();
1308 strlcpy(a->nick,u->nick,NICKMAX);
1309 strlcpy(a->ident,u->ident,15);
1310 strlcpy(a->dhost,u->dhost,160);
1311 strlcpy(a->host,u->host,160);
1312 strlcpy(a->fullname,u->fullname,128);
1313 strlcpy(a->server,u->server,256);
1314 a->signon = u->signon;
1316 /* MAX_WHOWAS: max number of /WHOWAS items
1317 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1318 * can be replaced by a newer one
1321 if (iter == whowas.end())
1323 if (whowas.size() >= WHOWAS_MAX)
1325 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1327 // 3600 seconds in an hour ;)
1328 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1330 // delete the old one
1331 if (i->second) delete i->second;
1332 // replace with new one
1334 log(DEBUG,"added WHOWAS entry, purged an old record");
1338 // no space left and user doesnt exist. Don't leave ram in use!
1339 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1344 log(DEBUG,"added fresh WHOWAS entry");
1345 whowas[a->nick] = a;
1350 log(DEBUG,"updated WHOWAS entry");
1351 if (iter->second) delete iter->second;
1357 /* add a client connection to the sockets list */
1358 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1362 user_hash::iterator iter;
1364 tempnick = ConvToStr(socket) + "-unknown";
1365 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1367 iter = clientlist.find(tempnick);
1370 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1371 // using one as a registered connection. As theyre per fd, we can also safely assume
1372 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1373 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1374 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1375 // issue in earlier alphas/betas
1376 if (iter != clientlist.end())
1378 userrec* goner = iter->second;
1380 clientlist.erase(iter);
1384 * It is OK to access the value here this way since we know
1385 * it exists, we just created it above.
1387 * At NO other time should you access a value in a map or a
1388 * hash_map this way.
1390 clientlist[tempnick] = new userrec();
1392 NonBlocking(socket);
1393 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1395 clientlist[tempnick]->fd = socket;
1396 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1397 strncpy(clientlist[tempnick]->host, host,160);
1398 strncpy(clientlist[tempnick]->dhost, host,160);
1399 strncpy(clientlist[tempnick]->server, ServerName,256);
1400 strncpy(clientlist[tempnick]->ident, "unknown",15);
1401 clientlist[tempnick]->registered = 0;
1402 clientlist[tempnick]->signon = TIME+dns_timeout;
1403 clientlist[tempnick]->lastping = 1;
1404 clientlist[tempnick]->port = port;
1405 strncpy(clientlist[tempnick]->ip,ip,16);
1407 // set the registration timeout for this user
1408 unsigned long class_regtimeout = 90;
1409 int class_flood = 0;
1410 long class_threshold = 5;
1411 long class_sqmax = 262144; // 256kb
1412 long class_rqmax = 4096; // 4k
1414 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1416 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1418 class_regtimeout = (unsigned long)i->registration_timeout;
1419 class_flood = i->flood;
1420 clientlist[tempnick]->pingmax = i->pingtime;
1421 class_threshold = i->threshold;
1422 class_sqmax = i->sendqmax;
1423 class_rqmax = i->recvqmax;
1428 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1429 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1430 clientlist[tempnick]->flood = class_flood;
1431 clientlist[tempnick]->threshold = class_threshold;
1432 clientlist[tempnick]->sendqmax = class_sqmax;
1433 clientlist[tempnick]->recvqmax = class_rqmax;
1435 for (int i = 0; i < MAXCHANS; i++)
1437 clientlist[tempnick]->chans[i].channel = NULL;
1438 clientlist[tempnick]->chans[i].uc_modes = 0;
1441 if (clientlist.size() == MAXCLIENTS)
1443 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1447 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1448 // its a pretty big but for the moment valid assumption:
1449 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1450 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1451 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1452 // which for the time being is a physical impossibility (even the largest networks dont have more
1453 // than about 10,000 users on ONE server!)
1456 kill_link(clientlist[tempnick],"Server is full");
1461 char* e = matches_exception(ip);
1464 char* r = matches_zline(ip);
1467 char reason[MAXBUF];
1468 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1469 kill_link(clientlist[tempnick],reason);
1473 fd_ref_table[socket] = clientlist[tempnick];
1476 struct epoll_event ev;
1477 log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1478 ev.events = EPOLLIN | EPOLLET;
1479 ev.data.fd = socket;
1480 int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1483 log(DEBUG,"epoll: List insertion failure!");
1488 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1489 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1490 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1493 log(DEBUG,"kqueue: List insertion failure!");
1499 /* shows the message of the day, and any other on-logon stuff */
1500 void FullConnectUser(userrec* user)
1503 user->idle_lastmsg = TIME;
1504 log(DEBUG,"ConnectUser: %s",user->nick);
1506 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1508 kill_link(user,"Invalid password");
1513 kill_link(user,"Unauthorised connection");
1517 char match_against[MAXBUF];
1518 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1519 char* e = matches_exception(match_against);
1522 char* r = matches_gline(match_against);
1525 char reason[MAXBUF];
1526 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1527 kill_link_silent(user,reason);
1530 r = matches_kline(user->host);
1533 char reason[MAXBUF];
1534 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1535 kill_link_silent(user,reason);
1540 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1541 user->registered = 7;
1543 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1544 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1545 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1546 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1547 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1548 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1549 std::stringstream v;
1550 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1551 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1552 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1554 std::string data005 = v.str();
1555 FOREACH_MOD On005Numeric(data005);
1556 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1557 // so i'd better split it :)
1558 std::stringstream out(data005);
1559 std::string token = "";
1560 std::string line5 = "";
1561 int token_counter = 0;
1565 line5 = line5 + token + " ";
1567 if ((token_counter >= 13) || (out.eof() == true))
1569 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1576 char buffer[MAXBUF];
1577 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);
1578 NetSendToAll(buffer);
1580 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1581 FOREACH_MOD OnUserConnect(user);
1582 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1586 /* shows the message of the day, and any other on-logon stuff */
1587 void ConnectUser(userrec *user)
1589 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1590 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1592 FullConnectUser(user);
1596 std::string GetVersionString()
1598 char Revision[] = "$Revision$";
1599 char versiondata[MAXBUF];
1600 char *s1 = Revision;
1602 char *v2 = strtok_r(s1," ",&savept);
1604 v2 = strtok_r(s1," ",&savept);
1607 char socketengine[] = "kqueue";
1610 char socketengine[] = "select";
1613 char socketengine[] = "epoll";
1615 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1619 void handle_version(char **parameters, int pcnt, userrec *user)
1623 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1627 if (!strcmp(parameters[0],"*"))
1629 for (int j = 0; j < 32; j++)
1633 for (int x = 0; x < me[j]->connectors.size(); x++)
1635 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());
1641 if (match(ServerName,parameters[0]))
1643 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1646 bool displayed = false, found = false;
1647 for (int j = 0; j < 32; j++)
1651 for (int x = 0; x < me[j]->connectors.size(); x++)
1653 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1656 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1659 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1665 if ((!displayed) && (found))
1667 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1672 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1679 // calls a handler function for a command
1681 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1683 for (int i = 0; i < cmdlist.size(); i++)
1685 if (!strcasecmp(cmdlist[i].command,commandname))
1687 if (cmdlist[i].handler_function)
1689 if (pcnt>=cmdlist[i].min_params)
1691 if (strchr(user->modes,cmdlist[i].flags_needed))
1693 cmdlist[i].handler_function(parameters,pcnt,user);
1701 void DoSplitEveryone()
1703 bool go_again = true;
1707 for (int i = 0; i < 32; i++)
1711 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1713 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1716 j->CloseConnection();
1717 me[i]->connectors.erase(j);
1725 log(DEBUG,"Removed server. Will remove clients...");
1726 // iterate through the userlist and remove all users on this server.
1727 // because we're dealing with a mesh, we dont have to deal with anything
1728 // "down-route" from this server (nice huh)
1730 char reason[MAXBUF];
1734 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1736 if (strcasecmp(u->second->server,ServerName))
1738 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1739 kill_link(u->second,reason);
1749 void force_nickchange(userrec* user,const char* newnick)
1756 FOREACH_RESULT(OnUserPreNick(user,newnick));
1759 kill_link(user,"Nickname collision");
1762 if (matches_qline(newnick))
1765 kill_link(user,"Nickname collision");
1773 strncpy(nick,newnick,MAXBUF);
1775 if (user->registered == 7)
1779 handle_nick(pars,1,user);
1785 int process_parameters(char **command_p,char *parameters)
1788 int q = strlen(parameters);
1791 /* no parameters, command_p invalid! */
1794 if (parameters[0] == ':')
1796 command_p[0] = parameters+1;
1801 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1803 /* only one parameter */
1804 command_p[0] = parameters;
1805 if (parameters[0] == ':')
1807 if (strchr(parameters,' ') != NULL)
1815 command_p[j++] = parameters;
1816 for (int i = 0; i <= q; i++)
1818 if (parameters[i] == ' ')
1820 command_p[j++] = parameters+i+1;
1821 parameters[i] = '\0';
1822 if (command_p[j-1][0] == ':')
1824 *command_p[j-1]++; /* remove dodgy ":" */
1826 /* parameter like this marks end of the sequence */
1830 return j; /* returns total number of items in the list */
1833 void process_command(userrec *user, char* cmd)
1837 char *command_p[127];
1838 char p[MAXBUF], temp[MAXBUF];
1839 int j, items, cmd_found;
1841 for (int i = 0; i < 127; i++)
1842 command_p[i] = NULL;
1857 int total_params = 0;
1860 for (int q = 0; q < strlen(cmd)-1; q++)
1862 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1865 // found a 'trailing', we dont count them after this.
1873 // another phidjit bug...
1874 if (total_params > 126)
1876 *(strchr(cmd,' ')) = '\0';
1877 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1881 strlcpy(temp,cmd,MAXBUF);
1883 std::string tmp = cmd;
1884 for (int i = 0; i <= MODCOUNT; i++)
1886 std::string oldtmp = tmp;
1887 modules[i]->OnServerRaw(tmp,true,user);
1890 log(DEBUG,"A Module changed the input string!");
1891 log(DEBUG,"New string: %s",tmp.c_str());
1892 log(DEBUG,"Old string: %s",oldtmp.c_str());
1896 strlcpy(cmd,tmp.c_str(),MAXBUF);
1897 strlcpy(temp,cmd,MAXBUF);
1899 if (!strchr(cmd,' '))
1901 /* no parameters, lets skip the formalities and not chop up
1903 log(DEBUG,"About to preprocess command with no params");
1905 command_p[0] = NULL;
1907 for (int i = 0; i <= strlen(cmd); i++)
1909 cmd[i] = toupper(cmd[i]);
1917 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1918 for (int i = 0; i < strlen(temp); i++)
1920 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1926 /* split the full string into a command plus parameters */
1930 if (strchr(cmd,' '))
1932 for (int i = 0; i <= strlen(cmd); i++)
1934 /* capitalise the command ONLY, leave params intact */
1935 cmd[i] = toupper(cmd[i]);
1936 /* are we nearly there yet?! :P */
1940 parameters = cmd+i+1;
1948 for (int i = 0; i <= strlen(cmd); i++)
1950 cmd[i] = toupper(cmd[i]);
1957 if (strlen(command)>MAXCOMMAND)
1959 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1963 for (int x = 0; x < strlen(command); x++)
1965 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1967 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1969 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1972 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1979 for (int i = 0; i != cmdlist.size(); i++)
1981 if (cmdlist[i].command[0])
1983 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1989 items = process_parameters(command_p,parameters);
1994 command_p[0] = NULL;
2000 command_p[0] = NULL;
2005 /* activity resets the ping pending timer */
2006 user->nping = TIME + user->pingmax;
2007 if ((items) < cmdlist[i].min_params)
2009 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2010 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2013 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2015 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2016 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2020 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2022 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2023 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2027 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2029 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2031 if ((!isnick(user->nick)) || (user->registered != 7))
2033 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2034 WriteServ(user->fd,"451 %s :You have not registered",command);
2038 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2042 mycmd = strtok_r(DisabledCommands," ",&savept2);
2045 if (!strcasecmp(mycmd,command))
2047 // command is disabled!
2048 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2051 mycmd = strtok_r(NULL," ",&savept2);
2056 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2058 if (cmdlist[i].handler_function)
2061 /* ikky /stats counters */
2064 cmdlist[i].use_count++;
2065 cmdlist[i].total_bytes+=strlen(temp);
2069 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2070 if (MOD_RESULT == 1) {
2074 /* WARNING: nothing may come after the
2075 * command handler call, as the handler
2076 * may free the user structure! */
2078 cmdlist[i].handler_function(command_p,items,user);
2084 WriteServ(user->fd,"451 %s :You have not registered",command);
2092 if ((!cmd_found) && (user))
2095 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2099 bool removecommands(const char* source)
2101 bool go_again = true;
2105 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2107 if (!strcmp(i->source,source))
2109 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2120 void process_buffer(const char* cmdbuf,userrec *user)
2124 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2130 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2137 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2139 strlcpy(cmd,cmdbuf,MAXBUF);
2144 int sl = strlen(cmd)-1;
2145 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2150 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2155 while (cmd[sl] == ' ') // strip trailing spaces
2165 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2167 if ((user) && (cmd))
2169 process_command(user,cmd);
2173 void DoSync(serverrec* serv, char* tcp_host)
2176 log(DEBUG,"Sending sync");
2177 // send start of sync marker: Y <timestamp>
2178 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2179 // except the ones its receiving it from.
2180 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2181 serv->SendPacket(data,tcp_host);
2182 // send users and channels
2184 NetSendMyRoutingTable();
2186 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2187 for (int j = 0; j < 32; j++)
2191 for (int k = 0; k < me[j]->connectors.size(); k++)
2193 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2195 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2196 serv->SendPacket(data,tcp_host);
2202 // send our version for the remote side to cache
2203 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2204 serv->SendPacket(data,tcp_host);
2206 // sync the users and channels, give the modules a look-in.
2207 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2209 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);
2210 serv->SendPacket(data,tcp_host);
2211 if (strchr(u->second->modes,'o'))
2213 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2214 serv->SendPacket(data,tcp_host);
2216 for (int i = 0; i <= MODCOUNT; i++)
2218 string_list l = modules[i]->OnUserSync(u->second);
2219 for (int j = 0; j < l.size(); j++)
2221 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2222 serv->SendPacket(data,tcp_host);
2225 char* chl = chlist(u->second,u->second);
2228 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2229 serv->SendPacket(data,tcp_host);
2232 // send channel modes, topics etc...
2233 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2235 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2236 serv->SendPacket(data,tcp_host);
2237 for (int i = 0; i <= MODCOUNT; i++)
2239 string_list l = modules[i]->OnChannelSync(c->second);
2240 for (int j = 0; j < l.size(); j++)
2242 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2243 serv->SendPacket(data,tcp_host);
2246 if (c->second->topic[0])
2248 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);
2249 serv->SendPacket(data,tcp_host);
2251 // send current banlist
2253 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2255 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2256 serv->SendPacket(data,tcp_host);
2259 // sync global zlines, glines, etc
2260 sync_xlines(serv,tcp_host);
2262 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2263 serv->SendPacket(data,tcp_host);
2264 log(DEBUG,"Sent sync");
2265 // ircd sends its serverlist after the end of sync here
2269 void NetSendMyRoutingTable()
2271 // send out a line saying what is reachable to us.
2272 // E.g. if A is linked to B C and D, send out:
2274 // if its only linked to B and D send out:
2276 // if it has no links, dont even send out the line at all.
2277 char buffer[MAXBUF];
2278 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2279 bool sendit = false;
2280 for (int i = 0; i < 32; i++)
2284 for (int j = 0; j < me[i]->connectors.size(); j++)
2286 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2288 strlcat(buffer," ",MAXBUF);
2289 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2296 NetSendToAll(buffer);
2300 void DoSplit(const char* params)
2302 bool go_again = true;
2306 for (int i = 0; i < 32; i++)
2310 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2312 if (!strcasecmp(j->GetServerName().c_str(),params))
2315 j->CloseConnection();
2316 me[i]->connectors.erase(j);
2324 log(DEBUG,"Removed server. Will remove clients...");
2325 // iterate through the userlist and remove all users on this server.
2326 // because we're dealing with a mesh, we dont have to deal with anything
2327 // "down-route" from this server (nice huh)
2329 char reason[MAXBUF];
2330 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2334 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2336 if (!strcasecmp(u->second->server,params))
2338 kill_link(u->second,reason);
2346 // removes a server. Will NOT remove its users!
2348 void RemoveServer(const char* name)
2350 bool go_again = true;
2354 for (int i = 0; i < 32; i++)
2358 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2360 if (!strcasecmp(j->GetServerName().c_str(),name))
2363 j->CloseConnection();
2364 me[i]->connectors.erase(j);
2375 char MODERR[MAXBUF];
2382 void erase_factory(int j)
2385 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2390 factory.push_back(NULL);
2397 void erase_module(int j)
2400 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2406 modules.push_back(NULL);
2412 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2416 module_names.erase(v);
2424 bool UnloadModule(const char* filename)
2426 std::string filename_str = filename;
2427 for (int j = 0; j != module_names.size(); j++)
2429 if (module_names[j] == filename_str)
2431 if (modules[j]->GetVersion().Flags & VF_STATIC)
2433 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2434 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2438 log(DEBUG,"Deleting module...");
2440 log(DEBUG,"Erasing module entry...");
2442 log(DEBUG,"Removing dependent commands...");
2443 removecommands(filename);
2444 log(DEFAULT,"Module %s unloaded",filename);
2449 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2450 snprintf(MODERR,MAXBUF,"Module not loaded");
2454 bool LoadModule(const char* filename)
2456 char modfile[MAXBUF];
2458 snprintf(modfile,MAXBUF,"%s",filename);
2460 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2462 std::string filename_str = filename;
2464 if (!DirValid(modfile))
2466 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2467 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2471 log(DEBUG,"Loading module: %s",modfile);
2473 if (FileExists(modfile))
2476 for (int j = 0; j < module_names.size(); j++)
2478 if (module_names[j] == filename_str)
2480 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2481 snprintf(MODERR,MAXBUF,"Module already loaded");
2485 ircd_module* a = new ircd_module(modfile);
2486 factory[MODCOUNT+1] = a;
2487 if (factory[MODCOUNT+1]->LastError())
2489 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2490 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2494 if (factory[MODCOUNT+1]->factory)
2496 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2497 modules[MODCOUNT+1] = m;
2498 /* save the module and the module's classfactory, if
2499 * this isnt done, random crashes can occur :/ */
2500 module_names.push_back(filename);
2504 log(DEFAULT,"Unable to load %s",modfile);
2505 snprintf(MODERR,MAXBUF,"Factory function failed!");
2512 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2513 snprintf(MODERR,MAXBUF,"Module file could not be found");
2522 bool GotServer(std::string name)
2524 for (int j = 0; j < 32; j++)
2528 for (int k = 0; k < me[j]->connectors.size(); k++)
2530 if (name == me[j]->connectors[k].GetServerName())
2541 int InspIRCd(char** argv, int argc)
2543 struct sockaddr_in client,server;
2544 char addrs[MAXBUF][255];
2545 int incomingSockfd, result = TRUE;
2548 int selectResult = 0, selectResult2 = 0;
2549 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2553 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2554 log_file = fopen(logpath.c_str(),"a+");
2557 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2562 printf("Logging to ircd.log...\n");
2564 printf("Logging to %s...\n",logpath.c_str());
2567 log(DEFAULT,"$Id$");
2570 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2572 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2574 SetupCommandTable();
2575 log(DEBUG,"InspIRCd: startup: default command table set up");
2577 ReadConfig(true,NULL);
2580 printf("WARNING: %s\n\n",DieValue);
2581 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2584 log(DEBUG,"InspIRCd: startup: read config");
2586 int clientportcount = 0, serverportcount = 0;
2588 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2590 ConfValue("bind","port",count,configToken,&config_f);
2591 ConfValue("bind","address",count,Addr,&config_f);
2592 ConfValue("bind","type",count,Type,&config_f);
2593 if (!strcmp(Type,"servers"))
2595 char Default[MAXBUF];
2596 strcpy(Default,"no");
2597 ConfValue("bind","default",count,Default,&config_f);
2598 if (strchr(Default,'y'))
2600 defaultRoute = serverportcount;
2601 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2603 me[serverportcount] = new serverrec(ServerName,100L,false);
2604 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2606 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2607 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2616 ports[clientportcount] = atoi(configToken);
2617 strlcpy(addrs[clientportcount],Addr,256);
2620 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2622 portCount = clientportcount;
2623 SERVERportCount = serverportcount;
2625 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2626 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2630 /* BugFix By Craig! :p */
2632 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2634 ConfValue("module","name",count,configToken,&config_f);
2635 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2636 if (!LoadModule(configToken))
2638 log(DEFAULT,"Exiting due to a module loader error.");
2639 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2643 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2645 startup_time = time(NULL);
2648 ConfValue("pid","file",0,PID,&config_f);
2649 // write once here, to try it out and make sure its ok
2652 /* setup select call */
2654 FD_ZERO(&selectFds);
2656 log(DEBUG,"InspIRCd: startup: zero selects");
2657 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2659 for (count = 0; count < portCount; count++)
2661 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2663 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2666 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2668 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2670 else /* well we at least bound to one socket so we'll continue */
2676 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2678 /* if we didn't bind to anything then abort */
2679 if (boundPortCount == 0)
2681 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2682 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2687 printf("\nInspIRCd is now running!\n");
2691 log(VERBOSE,"Not forking as -nofork was specified");
2695 if (DaemonSeed() == ERROR)
2697 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2698 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2703 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2708 if ((kq == -1) || (lkq == -1) || (skq == -1))
2710 log(DEFAULT,"main: kqueue() failed!");
2711 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2717 ep = epoll_create(MAXCLIENTS);
2718 lep = epoll_create(32);
2719 sep = epoll_create(128);
2720 if ((ep == -1) || (lep == -1) || (sep == -1))
2722 log(DEFAULT,"main: epoll_create() failed!");
2723 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2729 log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2730 for (count = 0; count < boundPortCount; count++)
2732 struct epoll_event ev;
2733 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2734 ev.events = EPOLLIN | EPOLLET;
2735 ev.data.fd = openSockfd[count];
2736 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2739 log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2740 printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2745 for (int t = 0; t != SERVERportCount; t++)
2747 struct epoll_event ev;
2748 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2749 ev.events = EPOLLIN | EPOLLET;
2750 ev.data.fd = me[t]->fd;
2751 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2754 log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2755 printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2761 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2762 for (count = 0; count < boundPortCount; count++)
2765 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2766 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2767 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2770 log(DEFAULT,"main: add listen ports to kqueue failed!");
2771 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2775 for (int t = 0; t != SERVERportCount; t++)
2780 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2781 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2782 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2785 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2786 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2794 log(DEFAULT,"Using standard select socket engine.");
2800 length = sizeof (client);
2801 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2805 struct kevent ke_list[33];
2809 struct epoll_event event[33];
2813 tvs.tv_usec = 10000L;
2816 tv.tv_usec = 10000L;
2820 tval.tv_usec = 10000L;
2822 int total_in_this_set = 0;
2823 int i = 0, v = 0, j = 0, cycle_iter = 0;
2824 bool expire_run = false;
2826 /* main loop, this never returns */
2829 #ifdef _POSIX_PRIORITY_SCHEDULING
2835 // we only read time() once per iteration rather than tons of times!
2841 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2842 // them in a list, then reap the list every second or so.
2843 if (((TIME % 5) == 0) && (!expire_run))
2845 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2847 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2848 ConfValue("link","name",i,Link_ServerName,&config_f);
2849 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2850 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2852 autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2853 if (a != autoconns.end())
2855 if (TIME > a->second)
2857 ConnectServer(Link_ServerName,NULL);
2858 a->second = TIME + atoi(Link_AConn);
2865 FOREACH_MOD OnBackgroundTimer(TIME);
2869 if ((TIME % 5) == 1)
2872 // fix by brain - this must be below any manipulation of the hashmap by modules
2873 user_hash::iterator count2 = clientlist.begin();
2876 i = epoll_wait(sep, event, 1, EP_DELAY);
2879 log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2880 for (int x = 0; x != SERVERportCount; x++)
2882 if ((me[x]) && (event[0].data.fd == me[x]->fd))
2887 ts.tv_nsec = 30000L;
2888 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2891 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2892 for (int x = 0; x != SERVERportCount; x++)
2894 if ((me[x]) && (ke.ident == me[x]->fd))
2899 FD_ZERO(&serverfds);
2900 for (int x = 0; x != SERVERportCount; x++)
2903 FD_SET(me[x]->fd, &serverfds);
2905 tvs.tv_usec = 30000L;
2907 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2910 for (int x = 0; x != SERVERportCount; x++)
2912 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2915 char remotehost[MAXBUF],resolved[MAXBUF];
2916 length = sizeof (client);
2917 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2918 if (incomingSockfd != -1)
2920 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2921 if(CleanAndResolve(resolved, remotehost) != TRUE)
2923 strlcpy(resolved,remotehost,MAXBUF);
2925 // add to this connections ircd_connector vector
2926 // *FIX* - we need the LOCAL port not the remote port in &client!
2927 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2933 std::deque<std::string> msgs;
2934 std::deque<std::string> sums;
2935 for (int x = 0; x < SERVERportCount; x++)
2938 me[x]->FlushWriteBuffers();
2941 while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2943 for (int ctr = 0; ctr < msgs.size(); ctr++)
2945 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2946 strlcpy(tcp_sum,msgs[ctr].c_str(),MAXBUF);
2947 log(DEBUG,"Processing: %s",tcp_msg);
2950 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2953 // during a netburst, send all data to all other linked servers
2954 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2956 if (is_uline(tcp_host))
2958 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2960 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2964 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2966 std::string msg = tcp_msg;
2967 FOREACH_MOD OnPacketReceive(msg,tcp_host);
2968 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2970 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2971 if (!me[x]->FindHost(tcp_host))
2973 log(DEBUG,"Connector gone, bailing!");
2977 sums.clear(); // we're done, clear the list for the next operation
2982 while (count2 != clientlist.end())
2988 total_in_this_set = 0;
2990 user_hash::iterator xcount = count2;
2991 user_hash::iterator endingiter = count2;
2993 if (count2 == clientlist.end()) break;
2995 userrec* curr = NULL;
2998 curr = count2->second;
3000 if ((long)curr == -1)
3003 if ((curr) && (curr->fd != 0))
3005 #ifdef _POSIX_PRIORITY_SCHEDULING
3008 // assemble up to 64 sockets into an fd_set
3009 // to implement a pooling mechanism.
3011 // This should be up to 64x faster than the
3012 // old implementation.
3014 while (total_in_this_set < 1024)
3016 if (count2 != clientlist.end())
3018 curr = count2->second;
3019 if ((long)curr == -1)
3021 int currfd = curr->fd;
3022 // we don't check the state of remote users.
3023 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3025 curr->FlushWriteBuf();
3026 if (curr->GetWriteError() != "")
3028 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3029 kill_link(curr,curr->GetWriteError().c_str());
3033 FD_SET (curr->fd, &sfd);
3035 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3036 // their connection class.
3037 if ((TIME > curr->timeout) && (curr->registered != 7))
3039 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3040 kill_link(curr,"Registration timeout");
3043 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3045 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3046 curr->dns_done = true;
3048 FullConnectUser(curr);
3049 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3052 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3054 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3055 FullConnectUser(curr);
3056 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3059 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3061 if ((!curr->lastping) && (curr->registered == 7))
3063 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3064 kill_link(curr,"Ping timeout");
3067 Write(curr->fd,"PING :%s",ServerName);
3068 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3070 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3074 total_in_this_set++;
3078 endingiter = count2;
3079 count2 = xcount; // roll back to where we were
3081 // 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.
3082 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3084 if (cycle_iter > 20) while (count2 != clientlist.end())
3087 if (count2 != clientlist.end())
3089 curr = count2->second;
3090 if ((long)curr == -1)
3092 int currfd = curr->fd;
3093 // we don't check the state of remote users.
3094 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3097 curr->FlushWriteBuf();
3098 if (curr->GetWriteError() != "")
3100 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3101 kill_link(curr,curr->GetWriteError().c_str());
3105 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3106 // their connection class.
3107 if ((TIME > curr->timeout) && (curr->registered != 7))
3109 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3110 kill_link(curr,"Registration timeout");
3114 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3116 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3117 curr->dns_done = true;
3119 FullConnectUser(curr);
3120 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3123 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3125 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3126 FullConnectUser(curr);
3127 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3130 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3132 if ((!curr->lastping) && (curr->registered == 7))
3134 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3135 kill_link(curr,"Ping timeout");
3138 Write(curr->fd,"PING :%s",ServerName);
3139 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3141 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3148 // increment the counter right to the end of the list, as kqueue processes everything in one go
3153 int i = epoll_wait(ep, event, 1, 5);
3156 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3157 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3158 userrec* cu = fd_ref_table[event[0].data.fd];
3163 // for now, we only read 1 event. We could read soooo many more :)
3164 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3167 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3168 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3169 userrec* cu = fd_ref_table[ke.ident];
3173 tval.tv_usec = 1000L;
3174 selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3175 // now loop through all of the items in this pool if any are waiting
3176 if ((selectResult2 > 0) && (xcount != clientlist.end()))
3177 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3179 // SELECT: we have to iterate...
3180 if (count2a == clientlist.end())
3182 userrec* cu = count2a->second;
3185 #ifdef _POSIX_PRIORITY_SCHEDULING
3190 // EPOLL: We already know we have a valid FD. No checks needed.
3191 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3194 // KQUEUE: We already know we have a valid FD. No checks needed.
3195 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3198 // SELECT: We don't know if our FD is valid.
3199 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3202 log(DEBUG,"Data waiting on socket %d",cu->fd);
3205 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3208 result = cu->ReadData(data, 65535);
3210 else result = result2;
3211 log(DEBUG,"Read result: %d",result);
3214 statsRecv += result;
3215 // perform a check on the raw buffer as an array (not a string!) to remove
3216 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3217 // hopefully this should stop even more people whining about "Unknown command: *"
3218 for (int checker = 0; checker < result; checker++)
3220 if ((data[checker] == 0) || (data[checker] == 7))
3221 data[checker] = ' ';
3224 data[result] = '\0';
3225 userrec* current = cu;
3226 int currfd = current->fd;
3228 // add the data to the users buffer
3230 if (!current->AddBuffer(data))
3232 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3233 if (current->registered == 7)
3235 kill_link(current,"RecvQ exceeded");
3239 WriteOpers("*** Excess flood from %s",current->ip);
3240 log(DEFAULT,"Excess flood from: %s",current->ip);
3241 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3246 if (current->recvq.length() > NetBufferSize)
3248 if (current->registered == 7)
3250 kill_link(current,"RecvQ exceeded");
3254 WriteOpers("*** Excess flood from %s",current->ip);
3255 log(DEFAULT,"Excess flood from: %s",current->ip);
3256 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3261 // while there are complete lines to process...
3262 while (current->BufferIsReady())
3265 if (TIME > current->reset_due)
3267 current->reset_due = TIME + current->threshold;
3268 current->lines_in = 0;
3270 current->lines_in++;
3271 if (current->lines_in > current->flood)
3273 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3274 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3275 kill_link(current,"Excess flood");
3278 if ((floodlines > current->flood) && (current->flood != 0))
3280 if (current->registered == 7)
3282 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3283 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3284 kill_link(current,"Excess flood");
3288 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3293 char sanitized[MAXBUF];
3294 // use GetBuffer to copy single lines into the sanitized string
3295 std::string single_line = current->GetBuffer();
3296 current->bytes_in += single_line.length();
3298 if (single_line.length()>512)
3300 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3301 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3302 kill_link(current,"Excess flood");
3305 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3308 userrec* old_comp = fd_ref_table[currfd];
3309 // we're gonna re-scan to check if the nick is gone, after every
3310 // command - if it has, we're gonna bail
3311 process_buffer(sanitized,current);
3312 // look for the user's record in case it's changed... if theyve quit,
3313 // we cant do anything more with their buffer, so bail.
3314 // there used to be an ugly, slow loop here. Now we have a reference
3315 // table, life is much easier (and FASTER)
3316 userrec* new_comp = fd_ref_table[currfd];
3317 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3325 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3327 log(DEBUG,"killing: %s",cu->nick);
3328 kill_link(cu,strerror(errno));
3332 // result EAGAIN means nothing read
3333 if (result == EAGAIN)
3343 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3344 kill_link(cu,"Client exited");
3345 // must bail here? kill_link removes the hash, corrupting the iterator
3346 log(DEBUG,"Bailing from client exit");
3352 else if (result > 0)
3357 for (int q = 0; q < total_in_this_set; q++)
3363 #ifdef _POSIX_PRIORITY_SCHEDULING
3368 // set up select call
3369 for (count = 0; count < boundPortCount; count++)
3371 FD_SET (openSockfd[count], &selectFds);
3374 tv.tv_usec = 30000L;
3375 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3377 /* select is reporting a waiting socket. Poll them all to find out which */
3378 if (selectResult > 0)
3380 for (count = 0; count < boundPortCount; count++)
3382 if (FD_ISSET (openSockfd[count], &selectFds))
3387 ts.tv_nsec = 30000L;
3388 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3389 if (i > 0) for (j = 0; j < i; j++)
3391 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3392 // this isnt as efficient as it could be, we could create a reference table
3393 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3394 // number of listening ports on the average ircd is a small number (less than 20)
3395 // compared to the number of clients (possibly over 2000)
3396 for (count = 0; count < boundPortCount; count++)
3398 if (ke_list[j].ident == openSockfd[count])
3402 i = epoll_wait(lep, event, 32, EP_DELAY);
3403 if (i > 0) for (j = 0; j < i; j++)
3405 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3406 for (count = 0; count < boundPortCount; count++)
3408 if (event[j].data.fd == openSockfd[count])
3411 char target[MAXBUF], resolved[MAXBUF];
3412 length = sizeof (client);
3413 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3415 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3416 strlcpy (resolved, target, MAXBUF);
3418 if (incomingSockfd < 0)
3420 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3421 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3426 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3428 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3429 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3436 #ifdef _POSIX_PRIORITY_SCHEDULING
3442 close (incomingSockfd);