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 bool has_been_netsplit = false;
124 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
125 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
126 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
127 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
128 typedef std::deque<command_t> command_table;
129 typedef std::map<std::string,time_t> autoconnects;
131 // This table references users by file descriptor.
132 // its an array to make it VERY fast, as all lookups are referenced
133 // by an integer, meaning there is no need for a scan/search operation.
134 userrec* fd_ref_table[65536];
136 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
142 user_hash clientlist;
145 command_table cmdlist;
146 autoconnects autoconns;
153 struct linger linger = { 0 };
154 char MyExecutable[1024];
155 int boundPortCount = 0;
156 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
157 int defaultRoute = 0;
158 char ModPath[MAXBUF];
162 int has_channel(userrec *u, chanrec *c);
163 int usercount(chanrec *c);
164 int usercount_i(chanrec *c);
165 char* Passwd(userrec *user);
166 bool IsDenied(userrec *user);
167 void AddWhoWas(userrec* u);
169 std::vector<long> auth_cookies;
170 std::stringstream config_f(stringstream::in | stringstream::out);
172 std::vector<userrec*> all_opers;
176 void AddOper(userrec* user)
178 log(DEBUG,"Oper added to optimization list");
179 all_opers.push_back(user);
182 void DeleteOper(userrec* user)
184 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
188 log(DEBUG,"Oper removed from optimization list");
195 std::string GetRevision()
197 char Revision[] = "$Revision$";
200 char *v2 = strtok_r(s1," ",&savept);
202 v2 = strtok_r(s1," ",&savept);
204 return std::string(v2);
208 std::string getservername()
213 std::string getserverdesc()
218 std::string getnetworkname()
223 std::string getadminname()
228 std::string getadminemail()
233 std::string getadminnick()
238 void ReadConfig(bool bail, userrec* user)
240 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
241 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
243 std::stringstream errstr;
245 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
250 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
258 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
259 while (!errstr.eof())
261 errstr.getline(dataline,1024);
262 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
267 WriteOpers("There were errors in the configuration file:",user->nick);
268 while (!errstr.eof())
270 errstr.getline(dataline,1024);
271 WriteOpers(dataline);
278 ConfValue("server","name",0,ServerName,&config_f);
279 ConfValue("server","description",0,ServerDesc,&config_f);
280 ConfValue("server","network",0,Network,&config_f);
281 ConfValue("admin","name",0,AdminName,&config_f);
282 ConfValue("admin","email",0,AdminEmail,&config_f);
283 ConfValue("admin","nick",0,AdminNick,&config_f);
284 ConfValue("files","motd",0,motd,&config_f);
285 ConfValue("files","rules",0,rules,&config_f);
286 ConfValue("power","diepass",0,diepass,&config_f);
287 ConfValue("power","pause",0,pauseval,&config_f);
288 ConfValue("power","restartpass",0,restartpass,&config_f);
289 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
290 ConfValue("die","value",0,DieValue,&config_f);
291 ConfValue("options","loglevel",0,dbg,&config_f);
292 ConfValue("options","netbuffersize",0,NB,&config_f);
293 ConfValue("options","maxwho",0,MW,&config_f);
294 ConfValue("options","allowhalfop",0,AH,&config_f);
295 ConfValue("options","allowprotect",0,AP,&config_f);
296 ConfValue("options","allowfounder",0,AF,&config_f);
297 ConfValue("dns","server",0,DNSServer,&config_f);
298 ConfValue("dns","timeout",0,DNT,&config_f);
299 ConfValue("options","moduledir",0,ModPath,&config_f);
300 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
301 ConfValue("options","somaxconn",0,MCON,&config_f);
303 MaxConn = atoi(MCON);
304 if (MaxConn > SOMAXCONN)
305 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
306 NetBufferSize = atoi(NB);
307 MaxWhoResults = atoi(MW);
308 dns_timeout = atoi(DNT);
314 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
316 strlcpy(ModPath,MOD_PATH,MAXBUF);
317 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
318 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
319 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
320 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
322 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
323 NetBufferSize = 10240;
325 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
327 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
330 if (!strcmp(dbg,"debug"))
332 if (!strcmp(dbg,"verbose"))
334 if (!strcmp(dbg,"default"))
336 if (!strcmp(dbg,"sparse"))
338 if (!strcmp(dbg,"none"))
341 log(DEFAULT,"Reading message of the day...");
342 readfile(RULES,rules);
343 log(DEFAULT,"Reading connect classes...");
345 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
348 ConfValue("connect","allow",i,Value,&config_f);
349 ConfValue("connect","timeout",i,timeout,&config_f);
350 ConfValue("connect","flood",i,flood,&config_f);
351 ConfValue("connect","pingfreq",i,pfreq,&config_f);
352 ConfValue("connect","threshold",i,thold,&config_f);
353 ConfValue("connect","sendq",i,sqmax,&config_f);
354 ConfValue("connect","recvq",i,rqmax,&config_f);
357 strlcpy(c.host,Value,MAXBUF);
359 strlcpy(Value,"",MAXBUF);
360 ConfValue("connect","password",i,Value,&config_f);
361 strlcpy(c.pass,Value,MAXBUF);
362 c.registration_timeout = 90; // default is 2 minutes
364 c.flood = atoi(flood);
366 c.sendqmax = 262144; // 256k
367 c.recvqmax = 4096; // 4k
370 c.threshold = atoi(thold);
374 c.sendqmax = atoi(sqmax);
378 c.recvqmax = atoi(rqmax);
382 c.registration_timeout = atoi(timeout);
386 c.pingtime = atoi(pfreq);
388 Classes.push_back(c);
389 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);
393 ConfValue("connect","deny",i,Value,&config_f);
394 strlcpy(c.host,Value,MAXBUF);
396 Classes.push_back(c);
397 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
401 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
402 read_xline_defaults();
403 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
407 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
409 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
410 ConfValue("link","name",i,Link_ServerName,&config_f);
411 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
412 if (strcmp(Link_AConn,""))
414 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
419 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
422 log(DEFAULT,"Adding and removing modules due to rehash...");
424 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
426 // store the old module names
427 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
429 old_module_names.push_back(*t);
432 // get the new module names
433 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
435 ConfValue("module","name",count2,Value,&config_f);
436 new_module_names.push_back(Value);
439 // now create a list of new modules that are due to be loaded
440 // and a seperate list of modules which are due to be unloaded
441 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
444 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
450 added_modules.push_back(*_new);
452 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
455 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
461 removed_modules.push_back(*oldm);
463 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
465 int rem = 0, add = 0;
466 if (!removed_modules.empty())
467 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
469 if (UnloadModule(removing->c_str()))
471 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
472 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
477 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
480 if (!added_modules.empty())
481 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
483 if (LoadModule(adding->c_str()))
485 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
486 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
491 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
494 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());
499 /* add a channel to a user, creating the record for it if needed and linking
500 * it to the user record */
502 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
504 if ((!user) || (!cn))
506 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
514 strncpy(cname,cn,MAXBUF);
516 // we MUST declare this wherever we use FOREACH_RESULT
519 if (strlen(cname) > CHANMAX-1)
521 cname[CHANMAX-1] = '\0';
524 log(DEBUG,"add_channel: %s %s",user->nick,cname);
526 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
528 return NULL; // already on the channel!
532 if (!FindChan(cname))
535 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
536 if (MOD_RESULT == 1) {
540 /* create a new one */
541 log(DEBUG,"add_channel: creating: %s",cname);
543 chanlist[cname] = new chanrec();
545 strlcpy(chanlist[cname]->name, cname,CHANMAX);
546 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
547 chanlist[cname]->created = TIME;
548 strcpy(chanlist[cname]->topic, "");
549 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
550 chanlist[cname]->topicset = 0;
551 Ptr = chanlist[cname];
552 log(DEBUG,"add_channel: created: %s",cname);
553 /* set created to 2 to indicate user
554 * is the first in the channel
555 * and should be given ops */
561 /* channel exists, just fish out a pointer to its struct */
562 Ptr = FindChan(cname);
565 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
567 // the override flag allows us to bypass channel modes
568 // and bans (used by servers)
569 if ((!override) || (!strcasecmp(user->server,ServerName)))
571 log(DEBUG,"Not overriding...");
573 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
574 if (MOD_RESULT == 1) {
577 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
581 log(DEBUG,"add_channel: checking key, invite, etc");
583 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
588 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
591 log(DEBUG,"add_channel: no key given in JOIN");
592 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
597 if (strcasecmp(key,Ptr->key))
599 log(DEBUG,"add_channel: bad key given in JOIN");
600 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
605 log(DEBUG,"add_channel: no key");
608 FOREACH_RESULT(OnCheckInvite(user, Ptr));
611 if (Ptr->binarymodes & CM_INVITEONLY)
613 log(DEBUG,"add_channel: channel is +i");
614 if (user->IsInvited(Ptr->name))
616 /* user was invited to channel */
617 /* there may be an optional channel NOTICE here */
621 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
625 log(DEBUG,"add_channel: channel is not +i");
628 FOREACH_RESULT(OnCheckLimit(user, Ptr));
633 if (usercount(Ptr) >= Ptr->limit)
635 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
640 log(DEBUG,"add_channel: about to walk banlist");
642 FOREACH_RESULT(OnCheckBan(user, Ptr));
645 /* check user against the channel banlist */
648 if (Ptr->bans.size())
650 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
652 if (match(user->GetFullHost(),i->data))
654 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
660 log(DEBUG,"add_channel: bans checked");
668 user->RemoveInvite(Ptr->name);
671 log(DEBUG,"add_channel: invites removed");
676 log(DEBUG,"Overridden checks");
684 log(DEBUG,"Passed channel checks");
686 for (int index =0; index != MAXCHANS; index++)
688 log(DEBUG,"Check location %d",index);
689 if (user->chans[index].channel == NULL)
691 log(DEBUG,"Adding into their channel list at location %d",index);
695 /* first user in is given ops */
696 user->chans[index].uc_modes = UCMODE_OP;
700 user->chans[index].uc_modes = 0;
702 user->chans[index].channel = Ptr;
703 Ptr->AddUser((char*)user);
704 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
706 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
708 // use the stamdard J token with no privilages.
712 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
716 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
718 NetSendToAll(buffer);
721 log(DEBUG,"Sent JOIN to client");
725 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
726 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
729 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
730 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
731 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
732 FOREACH_MOD OnUserJoin(user,Ptr);
736 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
737 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
741 /* remove a channel from a users record, and remove the record from memory
742 * if the channel has become empty */
744 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
746 if ((!user) || (!cname))
748 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
754 if ((!cname) || (!user))
759 Ptr = FindChan(cname);
766 FOREACH_MOD OnUserPart(user,Ptr);
767 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
769 for (int i =0; i != MAXCHANS; i++)
771 /* zap it from the channel list of the user */
772 if (user->chans[i].channel == Ptr)
776 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
781 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
782 NetSendToAll(buffer);
792 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
793 NetSendToAll(buffer);
796 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
798 user->chans[i].uc_modes = 0;
799 user->chans[i].channel = NULL;
800 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
805 Ptr->DelUser((char*)user);
807 /* if there are no users left on the channel */
810 chan_hash::iterator iter = chanlist.find(Ptr->name);
812 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
814 /* kill the record */
815 if (iter != chanlist.end())
817 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
819 chanlist.erase(iter);
825 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
827 if ((!src) || (!user) || (!Ptr) || (!reason))
829 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
833 if ((!Ptr) || (!user) || (!src))
838 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
840 if (!has_channel(user,Ptr))
842 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
847 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
848 if (MOD_RESULT == ACR_DENY)
851 if (MOD_RESULT == ACR_DEFAULT)
853 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
855 if (cstatus(src,Ptr) == STATUS_HOP)
857 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
861 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
869 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
873 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
875 for (int i =0; i != MAXCHANS; i++)
877 /* zap it from the channel list of the user */
878 if (user->chans[i].channel)
879 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
881 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
882 user->chans[i].uc_modes = 0;
883 user->chans[i].channel = NULL;
884 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
889 Ptr->DelUser((char*)user);
891 /* if there are no users left on the channel */
894 chan_hash::iterator iter = chanlist.find(Ptr->name);
896 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
898 /* kill the record */
899 if (iter != chanlist.end())
901 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
903 chanlist.erase(iter);
911 /* This function pokes and hacks at a parameter list like the following:
913 * PART #winbot,#darkgalaxy :m00!
915 * to turn it into a series of individual calls like this:
918 * PART #darkgalaxy :m00!
920 * The seperate calls are sent to a callback function provided by the caller
921 * (the caller will usually call itself recursively). The callback function
922 * must be a command handler. Calling this function on a line with no list causes
923 * no action to be taken. You must provide a starting and ending parameter number
924 * where the range of the list can be found, useful if you have a terminating
925 * parameter as above which is actually not part of the list, or parameters
926 * before the actual list as well. This code is used by many functions which
927 * can function as "one to list" (see the RFC) */
929 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
934 char blog[32][MAXBUF];
935 char blog2[32][MAXBUF];
936 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
940 for (int i = 0; i <32; i++)
943 for (int i = 0; i <32; i++)
947 for (int i = 0; i <10; i++)
956 if (pcnt > 1) /* we have a key to copy */
958 strlcpy(keystr,parameters[1],MAXBUF);
962 if (!parameters[start])
966 if (!strchr(parameters[start],','))
971 for (int i = start; i <= end; i++)
975 strlcat(plist,parameters[i],MAXBUF);
983 for (int i = 0; i < t; i++)
988 strlcpy(blog[j++],param,MAXBUF);
992 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
997 strlcpy(blog[j++],param,MAXBUF);
1000 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1005 if ((joins) && (keystr))
1007 if (strchr(keystr,','))
1011 t2 = strlen(keystr);
1012 for (int i = 0; i < t2; i++)
1014 if (keystr[i] == ',')
1017 strlcpy(blog2[j++],param,MAXBUF);
1021 strlcpy(blog2[j++],param,MAXBUF);
1026 for (j = 0; j < total; j++)
1032 for (q = end; q < pcnt-1; q++)
1034 if (parameters[q+1])
1036 pars[q-end+1] = parameters[q+1];
1039 if ((joins) && (parameters[1]))
1050 /* repeatedly call the function with the hacked parameter list */
1051 if ((joins) && (pcnt > 1))
1055 // pars[1] already set up and containing key from blog2[j]
1060 pars[1] = parameters[1];
1066 fn(pars,pcnt-(end-start),u);
1075 void kill_link(userrec *user,const char* r)
1077 user_hash::iterator iter = clientlist.find(user->nick);
1079 char reason[MAXBUF];
1081 strncpy(reason,r,MAXBUF);
1083 if (strlen(reason)>MAXQUIT)
1085 reason[MAXQUIT-1] = '\0';
1088 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1089 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1090 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1092 if (user->registered == 7) {
1093 FOREACH_MOD OnUserQuit(user);
1094 WriteCommonExcept(user,"QUIT :%s",reason);
1096 // Q token must go to ALL servers!!!
1097 char buffer[MAXBUF];
1098 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1099 NetSendToAll(buffer);
1102 user->FlushWriteBuf();
1104 FOREACH_MOD OnUserDisconnect(user);
1108 FOREACH_MOD OnRawSocketClose(user->fd);
1111 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1112 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1115 log(DEBUG,"kqueue: Failed to remove user from queue!");
1119 struct epoll_event ev;
1120 ev.events = EPOLLIN | EPOLLET;
1121 ev.data.fd = user->fd;
1122 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1125 log(DEBUG,"epoll: List deletion failure!");
1128 user->CloseSocket();
1131 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1132 // if they were an oper with +s.
1133 if (user->registered == 7) {
1134 purge_empty_chans(user);
1135 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1139 if (iter != clientlist.end())
1141 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1143 fd_ref_table[user->fd] = NULL;
1144 clientlist.erase(iter);
1149 void kill_link_silent(userrec *user,const char* r)
1151 user_hash::iterator iter = clientlist.find(user->nick);
1153 char reason[MAXBUF];
1155 strncpy(reason,r,MAXBUF);
1157 if (strlen(reason)>MAXQUIT)
1159 reason[MAXQUIT-1] = '\0';
1162 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1163 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1164 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1166 user->FlushWriteBuf();
1168 if (user->registered == 7) {
1169 FOREACH_MOD OnUserQuit(user);
1170 WriteCommonExcept(user,"QUIT :%s",reason);
1172 // Q token must go to ALL servers!!!
1173 char buffer[MAXBUF];
1174 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1175 NetSendToAll(buffer);
1178 FOREACH_MOD OnUserDisconnect(user);
1182 FOREACH_MOD OnRawSocketClose(user->fd);
1185 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1186 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1189 log(DEBUG,"kqueue: Failed to remove user from queue!");
1193 struct epoll_event ev;
1194 ev.events = EPOLLIN | EPOLLET;
1195 ev.data.fd = user->fd;
1196 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1199 log(DEBUG,"epoll: List deletion failure!");
1202 user->CloseSocket();
1205 if (user->registered == 7) {
1206 purge_empty_chans(user);
1209 if (iter != clientlist.end())
1211 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1213 fd_ref_table[user->fd] = NULL;
1214 clientlist.erase(iter);
1220 int main(int argc, char** argv)
1224 log(DEBUG,"*** InspIRCd starting up!");
1225 if (!FileExists(CONFIG_FILE))
1227 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1228 log(DEFAULT,"main: no config");
1229 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1233 for (int i = 1; i < argc; i++)
1235 if (!strcmp(argv[i],"-nofork")) {
1238 if (!strcmp(argv[i],"-wait")) {
1241 if (!strcmp(argv[i],"-nolimit")) {
1246 strlcpy(MyExecutable,argv[0],MAXBUF);
1248 // initialize the lowercase mapping table
1249 for (int cn = 0; cn < 256; cn++)
1251 // lowercase the uppercase chars
1252 for (int cn = 65; cn < 91; cn++)
1253 lowermap[cn] = tolower(cn);
1254 // now replace the specific chars for scandanavian comparison
1255 lowermap['['] = '{';
1256 lowermap[']'] = '}';
1257 lowermap['\\'] = '|';
1259 if (InspIRCd(argv,argc) == ERROR)
1261 log(DEFAULT,"main: daemon function bailed");
1262 printf("ERROR: could not initialise. Shutting down.\n");
1269 template<typename T> inline string ConvToStr(const T &in)
1272 if (!(tmp << in)) return string();
1276 /* re-allocates a nick in the user_hash after they change nicknames,
1277 * returns a pointer to the new user as it may have moved */
1279 userrec* ReHashNick(char* Old, char* New)
1281 //user_hash::iterator newnick;
1282 user_hash::iterator oldnick = clientlist.find(Old);
1284 log(DEBUG,"ReHashNick: %s %s",Old,New);
1286 if (!strcasecmp(Old,New))
1288 log(DEBUG,"old nick is new nick, skipping");
1289 return oldnick->second;
1292 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1294 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1296 userrec* olduser = oldnick->second;
1297 clientlist[New] = olduser;
1298 clientlist.erase(oldnick);
1300 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1302 return clientlist[New];
1305 /* adds or updates an entry in the whowas list */
1306 void AddWhoWas(userrec* u)
1308 whowas_hash::iterator iter = whowas.find(u->nick);
1309 WhoWasUser *a = new WhoWasUser();
1310 strlcpy(a->nick,u->nick,NICKMAX);
1311 strlcpy(a->ident,u->ident,15);
1312 strlcpy(a->dhost,u->dhost,160);
1313 strlcpy(a->host,u->host,160);
1314 strlcpy(a->fullname,u->fullname,128);
1315 strlcpy(a->server,u->server,256);
1316 a->signon = u->signon;
1318 /* MAX_WHOWAS: max number of /WHOWAS items
1319 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1320 * can be replaced by a newer one
1323 if (iter == whowas.end())
1325 if (whowas.size() >= WHOWAS_MAX)
1327 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1329 // 3600 seconds in an hour ;)
1330 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1332 // delete the old one
1333 if (i->second) delete i->second;
1334 // replace with new one
1336 log(DEBUG,"added WHOWAS entry, purged an old record");
1340 // no space left and user doesnt exist. Don't leave ram in use!
1341 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1346 log(DEBUG,"added fresh WHOWAS entry");
1347 whowas[a->nick] = a;
1352 log(DEBUG,"updated WHOWAS entry");
1353 if (iter->second) delete iter->second;
1359 /* add a client connection to the sockets list */
1360 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1364 user_hash::iterator iter;
1366 tempnick = ConvToStr(socket) + "-unknown";
1367 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1369 iter = clientlist.find(tempnick);
1372 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1373 // using one as a registered connection. As theyre per fd, we can also safely assume
1374 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1375 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1376 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1377 // issue in earlier alphas/betas
1378 if (iter != clientlist.end())
1380 userrec* goner = iter->second;
1382 clientlist.erase(iter);
1386 * It is OK to access the value here this way since we know
1387 * it exists, we just created it above.
1389 * At NO other time should you access a value in a map or a
1390 * hash_map this way.
1392 clientlist[tempnick] = new userrec();
1394 NonBlocking(socket);
1395 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1397 clientlist[tempnick]->fd = socket;
1398 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1399 strncpy(clientlist[tempnick]->host, host,160);
1400 strncpy(clientlist[tempnick]->dhost, host,160);
1401 strncpy(clientlist[tempnick]->server, ServerName,256);
1402 strncpy(clientlist[tempnick]->ident, "unknown",15);
1403 clientlist[tempnick]->registered = 0;
1404 clientlist[tempnick]->signon = TIME+dns_timeout;
1405 clientlist[tempnick]->lastping = 1;
1406 clientlist[tempnick]->port = port;
1407 strncpy(clientlist[tempnick]->ip,ip,16);
1409 // set the registration timeout for this user
1410 unsigned long class_regtimeout = 90;
1411 int class_flood = 0;
1412 long class_threshold = 5;
1413 long class_sqmax = 262144; // 256kb
1414 long class_rqmax = 4096; // 4k
1416 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1418 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1420 class_regtimeout = (unsigned long)i->registration_timeout;
1421 class_flood = i->flood;
1422 clientlist[tempnick]->pingmax = i->pingtime;
1423 class_threshold = i->threshold;
1424 class_sqmax = i->sendqmax;
1425 class_rqmax = i->recvqmax;
1430 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1431 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1432 clientlist[tempnick]->flood = class_flood;
1433 clientlist[tempnick]->threshold = class_threshold;
1434 clientlist[tempnick]->sendqmax = class_sqmax;
1435 clientlist[tempnick]->recvqmax = class_rqmax;
1437 for (int i = 0; i < MAXCHANS; i++)
1439 clientlist[tempnick]->chans[i].channel = NULL;
1440 clientlist[tempnick]->chans[i].uc_modes = 0;
1443 if (clientlist.size() == MAXCLIENTS)
1445 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1449 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1450 // its a pretty big but for the moment valid assumption:
1451 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1452 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1453 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1454 // which for the time being is a physical impossibility (even the largest networks dont have more
1455 // than about 10,000 users on ONE server!)
1458 kill_link(clientlist[tempnick],"Server is full");
1463 char* e = matches_exception(ip);
1466 char* r = matches_zline(ip);
1469 char reason[MAXBUF];
1470 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1471 kill_link(clientlist[tempnick],reason);
1475 fd_ref_table[socket] = clientlist[tempnick];
1478 struct epoll_event ev;
1479 log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1480 ev.events = EPOLLIN | EPOLLET;
1481 ev.data.fd = socket;
1482 int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1485 log(DEBUG,"epoll: List insertion failure!");
1490 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1491 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1492 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1495 log(DEBUG,"kqueue: List insertion failure!");
1501 /* shows the message of the day, and any other on-logon stuff */
1502 void FullConnectUser(userrec* user)
1505 user->idle_lastmsg = TIME;
1506 log(DEBUG,"ConnectUser: %s",user->nick);
1508 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1510 kill_link(user,"Invalid password");
1515 kill_link(user,"Unauthorised connection");
1519 char match_against[MAXBUF];
1520 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1521 char* e = matches_exception(match_against);
1524 char* r = matches_gline(match_against);
1527 char reason[MAXBUF];
1528 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1529 kill_link_silent(user,reason);
1532 r = matches_kline(user->host);
1535 char reason[MAXBUF];
1536 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1537 kill_link_silent(user,reason);
1542 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1543 user->registered = 7;
1545 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1546 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1547 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1548 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1549 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1550 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1551 std::stringstream v;
1552 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1553 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1554 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1556 std::string data005 = v.str();
1557 FOREACH_MOD On005Numeric(data005);
1558 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1559 // so i'd better split it :)
1560 std::stringstream out(data005);
1561 std::string token = "";
1562 std::string line5 = "";
1563 int token_counter = 0;
1567 line5 = line5 + token + " ";
1569 if ((token_counter >= 13) || (out.eof() == true))
1571 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1578 char buffer[MAXBUF];
1579 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);
1580 NetSendToAll(buffer);
1582 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1583 FOREACH_MOD OnUserConnect(user);
1584 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1588 /* shows the message of the day, and any other on-logon stuff */
1589 void ConnectUser(userrec *user)
1591 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1592 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1594 FullConnectUser(user);
1598 std::string GetVersionString()
1600 char Revision[] = "$Revision$";
1601 char versiondata[MAXBUF];
1602 char *s1 = Revision;
1604 char *v2 = strtok_r(s1," ",&savept);
1606 v2 = strtok_r(s1," ",&savept);
1609 char socketengine[] = "kqueue";
1612 char socketengine[] = "select";
1615 char socketengine[] = "epoll";
1617 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1621 void handle_version(char **parameters, int pcnt, userrec *user)
1625 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1629 if (!strcmp(parameters[0],"*"))
1631 for (int j = 0; j < 32; j++)
1635 for (int x = 0; x < me[j]->connectors.size(); x++)
1637 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());
1643 if (match(ServerName,parameters[0]))
1645 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1648 bool displayed = false, found = false;
1649 for (int j = 0; j < 32; j++)
1653 for (int x = 0; x < me[j]->connectors.size(); x++)
1655 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1658 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1661 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1667 if ((!displayed) && (found))
1669 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1674 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1681 // calls a handler function for a command
1683 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1685 for (int i = 0; i < cmdlist.size(); i++)
1687 if (!strcasecmp(cmdlist[i].command,commandname))
1689 if (cmdlist[i].handler_function)
1691 if (pcnt>=cmdlist[i].min_params)
1693 if (strchr(user->modes,cmdlist[i].flags_needed))
1695 cmdlist[i].handler_function(parameters,pcnt,user);
1703 void DoSplitEveryone()
1705 bool go_again = true;
1709 for (int i = 0; i < 32; i++)
1713 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1715 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1718 j->CloseConnection();
1719 me[i]->connectors.erase(j);
1727 log(DEBUG,"Removed server. Will remove clients...");
1728 // iterate through the userlist and remove all users on this server.
1729 // because we're dealing with a mesh, we dont have to deal with anything
1730 // "down-route" from this server (nice huh)
1732 char reason[MAXBUF];
1736 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1738 if (strcasecmp(u->second->server,ServerName))
1740 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1741 kill_link(u->second,reason);
1747 has_been_netsplit = true;
1752 void force_nickchange(userrec* user,const char* newnick)
1759 FOREACH_RESULT(OnUserPreNick(user,newnick));
1762 kill_link(user,"Nickname collision");
1765 if (matches_qline(newnick))
1768 kill_link(user,"Nickname collision");
1776 strncpy(nick,newnick,MAXBUF);
1778 if (user->registered == 7)
1782 handle_nick(pars,1,user);
1788 int process_parameters(char **command_p,char *parameters)
1791 int q = strlen(parameters);
1794 /* no parameters, command_p invalid! */
1797 if (parameters[0] == ':')
1799 command_p[0] = parameters+1;
1804 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1806 /* only one parameter */
1807 command_p[0] = parameters;
1808 if (parameters[0] == ':')
1810 if (strchr(parameters,' ') != NULL)
1818 command_p[j++] = parameters;
1819 for (int i = 0; i <= q; i++)
1821 if (parameters[i] == ' ')
1823 command_p[j++] = parameters+i+1;
1824 parameters[i] = '\0';
1825 if (command_p[j-1][0] == ':')
1827 *command_p[j-1]++; /* remove dodgy ":" */
1829 /* parameter like this marks end of the sequence */
1833 return j; /* returns total number of items in the list */
1836 void process_command(userrec *user, char* cmd)
1840 char *command_p[127];
1841 char p[MAXBUF], temp[MAXBUF];
1842 int j, items, cmd_found;
1844 for (int i = 0; i < 127; i++)
1845 command_p[i] = NULL;
1860 int total_params = 0;
1863 for (int q = 0; q < strlen(cmd)-1; q++)
1865 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1868 // found a 'trailing', we dont count them after this.
1876 // another phidjit bug...
1877 if (total_params > 126)
1879 *(strchr(cmd,' ')) = '\0';
1880 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1884 strlcpy(temp,cmd,MAXBUF);
1886 std::string tmp = cmd;
1887 for (int i = 0; i <= MODCOUNT; i++)
1889 std::string oldtmp = tmp;
1890 modules[i]->OnServerRaw(tmp,true,user);
1893 log(DEBUG,"A Module changed the input string!");
1894 log(DEBUG,"New string: %s",tmp.c_str());
1895 log(DEBUG,"Old string: %s",oldtmp.c_str());
1899 strlcpy(cmd,tmp.c_str(),MAXBUF);
1900 strlcpy(temp,cmd,MAXBUF);
1902 if (!strchr(cmd,' '))
1904 /* no parameters, lets skip the formalities and not chop up
1906 log(DEBUG,"About to preprocess command with no params");
1908 command_p[0] = NULL;
1910 for (int i = 0; i <= strlen(cmd); i++)
1912 cmd[i] = toupper(cmd[i]);
1920 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1921 for (int i = 0; i < strlen(temp); i++)
1923 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1929 /* split the full string into a command plus parameters */
1933 if (strchr(cmd,' '))
1935 for (int i = 0; i <= strlen(cmd); i++)
1937 /* capitalise the command ONLY, leave params intact */
1938 cmd[i] = toupper(cmd[i]);
1939 /* are we nearly there yet?! :P */
1943 parameters = cmd+i+1;
1951 for (int i = 0; i <= strlen(cmd); i++)
1953 cmd[i] = toupper(cmd[i]);
1960 if (strlen(command)>MAXCOMMAND)
1962 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1966 for (int x = 0; x < strlen(command); x++)
1968 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1970 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1972 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1975 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1982 for (int i = 0; i != cmdlist.size(); i++)
1984 if (cmdlist[i].command[0])
1986 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1992 items = process_parameters(command_p,parameters);
1997 command_p[0] = NULL;
2003 command_p[0] = NULL;
2008 /* activity resets the ping pending timer */
2009 user->nping = TIME + user->pingmax;
2010 if ((items) < cmdlist[i].min_params)
2012 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2013 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2016 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2018 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2019 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2023 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2025 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2026 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2030 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2032 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2034 if ((!isnick(user->nick)) || (user->registered != 7))
2036 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2037 WriteServ(user->fd,"451 %s :You have not registered",command);
2041 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2045 mycmd = strtok_r(DisabledCommands," ",&savept2);
2048 if (!strcasecmp(mycmd,command))
2050 // command is disabled!
2051 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2054 mycmd = strtok_r(NULL," ",&savept2);
2059 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2061 if (cmdlist[i].handler_function)
2064 /* ikky /stats counters */
2067 cmdlist[i].use_count++;
2068 cmdlist[i].total_bytes+=strlen(temp);
2072 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2073 if (MOD_RESULT == 1) {
2077 /* WARNING: nothing may come after the
2078 * command handler call, as the handler
2079 * may free the user structure! */
2081 cmdlist[i].handler_function(command_p,items,user);
2087 WriteServ(user->fd,"451 %s :You have not registered",command);
2095 if ((!cmd_found) && (user))
2098 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2102 bool removecommands(const char* source)
2104 bool go_again = true;
2108 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2110 if (!strcmp(i->source,source))
2112 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2123 void process_buffer(const char* cmdbuf,userrec *user)
2127 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2133 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2140 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2142 strlcpy(cmd,cmdbuf,MAXBUF);
2147 int sl = strlen(cmd)-1;
2148 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2153 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2158 while (cmd[sl] == ' ') // strip trailing spaces
2168 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2170 if ((user) && (cmd))
2172 process_command(user,cmd);
2176 void DoSync(serverrec* serv, char* tcp_host)
2179 log(DEBUG,"Sending sync");
2180 // send start of sync marker: Y <timestamp>
2181 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2182 // except the ones its receiving it from.
2183 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2184 serv->SendPacket(data,tcp_host);
2185 // send users and channels
2187 NetSendMyRoutingTable();
2189 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2190 for (int j = 0; j < 32; j++)
2194 for (int k = 0; k < me[j]->connectors.size(); k++)
2196 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2198 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2199 serv->SendPacket(data,tcp_host);
2205 // send our version for the remote side to cache
2206 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2207 serv->SendPacket(data,tcp_host);
2209 // sync the users and channels, give the modules a look-in.
2210 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2212 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);
2213 serv->SendPacket(data,tcp_host);
2214 if (strchr(u->second->modes,'o'))
2216 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2217 serv->SendPacket(data,tcp_host);
2219 for (int i = 0; i <= MODCOUNT; i++)
2221 string_list l = modules[i]->OnUserSync(u->second);
2222 for (int j = 0; j < l.size(); j++)
2224 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2225 serv->SendPacket(data,tcp_host);
2228 char* chl = chlist(u->second,u->second);
2231 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2232 serv->SendPacket(data,tcp_host);
2235 // send channel modes, topics etc...
2236 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2238 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2239 serv->SendPacket(data,tcp_host);
2240 for (int i = 0; i <= MODCOUNT; i++)
2242 string_list l = modules[i]->OnChannelSync(c->second);
2243 for (int j = 0; j < l.size(); j++)
2245 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2246 serv->SendPacket(data,tcp_host);
2249 if (c->second->topic[0])
2251 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);
2252 serv->SendPacket(data,tcp_host);
2254 // send current banlist
2256 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2258 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2259 serv->SendPacket(data,tcp_host);
2262 // sync global zlines, glines, etc
2263 sync_xlines(serv,tcp_host);
2265 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2266 serv->SendPacket(data,tcp_host);
2267 log(DEBUG,"Sent sync");
2268 // ircd sends its serverlist after the end of sync here
2272 void NetSendMyRoutingTable()
2274 // send out a line saying what is reachable to us.
2275 // E.g. if A is linked to B C and D, send out:
2277 // if its only linked to B and D send out:
2279 // if it has no links, dont even send out the line at all.
2280 char buffer[MAXBUF];
2281 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2282 bool sendit = false;
2283 for (int i = 0; i < 32; i++)
2287 for (int j = 0; j < me[i]->connectors.size(); j++)
2289 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2291 strlcat(buffer," ",MAXBUF);
2292 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2299 NetSendToAll(buffer);
2303 void DoSplit(const char* params)
2305 bool go_again = true;
2309 for (int i = 0; i < 32; i++)
2313 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2315 if (!strcasecmp(j->GetServerName().c_str(),params))
2318 j->CloseConnection();
2319 me[i]->connectors.erase(j);
2327 log(DEBUG,"Removed server. Will remove clients...");
2328 // iterate through the userlist and remove all users on this server.
2329 // because we're dealing with a mesh, we dont have to deal with anything
2330 // "down-route" from this server (nice huh)
2332 char reason[MAXBUF];
2333 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2337 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2339 if (!strcasecmp(u->second->server,params))
2341 kill_link(u->second,reason);
2347 has_been_netsplit = true;
2350 // removes a server. Will NOT remove its users!
2352 void RemoveServer(const char* name)
2354 bool go_again = true;
2358 for (int i = 0; i < 32; i++)
2362 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2364 if (!strcasecmp(j->GetServerName().c_str(),name))
2367 j->CloseConnection();
2368 me[i]->connectors.erase(j);
2379 char MODERR[MAXBUF];
2386 void erase_factory(int j)
2389 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2394 factory.push_back(NULL);
2401 void erase_module(int j)
2404 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2410 modules.push_back(NULL);
2416 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2420 module_names.erase(v);
2428 bool UnloadModule(const char* filename)
2430 std::string filename_str = filename;
2431 for (int j = 0; j != module_names.size(); j++)
2433 if (module_names[j] == filename_str)
2435 if (modules[j]->GetVersion().Flags & VF_STATIC)
2437 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2438 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2442 log(DEBUG,"Deleting module...");
2444 log(DEBUG,"Erasing module entry...");
2446 log(DEBUG,"Removing dependent commands...");
2447 removecommands(filename);
2448 log(DEFAULT,"Module %s unloaded",filename);
2453 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2454 snprintf(MODERR,MAXBUF,"Module not loaded");
2458 bool LoadModule(const char* filename)
2460 char modfile[MAXBUF];
2462 snprintf(modfile,MAXBUF,"%s",filename);
2464 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2466 std::string filename_str = filename;
2468 if (!DirValid(modfile))
2470 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2471 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2475 log(DEBUG,"Loading module: %s",modfile);
2477 if (FileExists(modfile))
2480 for (int j = 0; j < module_names.size(); j++)
2482 if (module_names[j] == filename_str)
2484 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2485 snprintf(MODERR,MAXBUF,"Module already loaded");
2489 ircd_module* a = new ircd_module(modfile);
2490 factory[MODCOUNT+1] = a;
2491 if (factory[MODCOUNT+1]->LastError())
2493 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2494 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2498 if (factory[MODCOUNT+1]->factory)
2500 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2501 modules[MODCOUNT+1] = m;
2502 /* save the module and the module's classfactory, if
2503 * this isnt done, random crashes can occur :/ */
2504 module_names.push_back(filename);
2508 log(DEFAULT,"Unable to load %s",modfile);
2509 snprintf(MODERR,MAXBUF,"Factory function failed!");
2516 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2517 snprintf(MODERR,MAXBUF,"Module file could not be found");
2526 bool GotServer(std::string name)
2528 for (int j = 0; j < 32; j++)
2532 for (int k = 0; k < me[j]->connectors.size(); k++)
2534 if (name == me[j]->connectors[k].GetServerName())
2545 int InspIRCd(char** argv, int argc)
2547 struct sockaddr_in client,server;
2548 char addrs[MAXBUF][255];
2549 int incomingSockfd, result = TRUE;
2552 int selectResult = 0, selectResult2 = 0;
2553 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2557 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2558 log_file = fopen(logpath.c_str(),"a+");
2561 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2566 printf("Logging to ircd.log...\n");
2568 printf("Logging to %s...\n",logpath.c_str());
2571 log(DEFAULT,"$Id$");
2574 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2576 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2578 SetupCommandTable();
2579 log(DEBUG,"InspIRCd: startup: default command table set up");
2581 ReadConfig(true,NULL);
2584 printf("WARNING: %s\n\n",DieValue);
2585 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2588 log(DEBUG,"InspIRCd: startup: read config");
2590 int clientportcount = 0, serverportcount = 0;
2592 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2594 ConfValue("bind","port",count,configToken,&config_f);
2595 ConfValue("bind","address",count,Addr,&config_f);
2596 ConfValue("bind","type",count,Type,&config_f);
2597 if (!strcmp(Type,"servers"))
2599 char Default[MAXBUF];
2600 strcpy(Default,"no");
2601 ConfValue("bind","default",count,Default,&config_f);
2602 if (strchr(Default,'y'))
2604 defaultRoute = serverportcount;
2605 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2607 me[serverportcount] = new serverrec(ServerName,100L,false);
2608 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2610 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2611 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2620 ports[clientportcount] = atoi(configToken);
2621 strlcpy(addrs[clientportcount],Addr,256);
2624 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2626 portCount = clientportcount;
2627 SERVERportCount = serverportcount;
2629 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2630 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2634 /* BugFix By Craig! :p */
2636 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2638 ConfValue("module","name",count,configToken,&config_f);
2639 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2640 if (!LoadModule(configToken))
2642 log(DEFAULT,"Exiting due to a module loader error.");
2643 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2647 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2649 startup_time = time(NULL);
2652 ConfValue("pid","file",0,PID,&config_f);
2653 // write once here, to try it out and make sure its ok
2656 /* setup select call */
2658 FD_ZERO(&selectFds);
2660 log(DEBUG,"InspIRCd: startup: zero selects");
2661 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2663 for (count = 0; count < portCount; count++)
2665 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2667 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2670 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2672 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2674 else /* well we at least bound to one socket so we'll continue */
2680 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2682 /* if we didn't bind to anything then abort */
2683 if (boundPortCount == 0)
2685 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2686 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2691 printf("\nInspIRCd is now running!\n");
2695 log(VERBOSE,"Not forking as -nofork was specified");
2699 if (DaemonSeed() == ERROR)
2701 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2702 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2707 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2712 if ((kq == -1) || (lkq == -1) || (skq == -1))
2714 log(DEFAULT,"main: kqueue() failed!");
2715 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2721 ep = epoll_create(MAXCLIENTS);
2722 lep = epoll_create(32);
2723 sep = epoll_create(128);
2724 if ((ep == -1) || (lep == -1) || (sep == -1))
2726 log(DEFAULT,"main: epoll_create() failed!");
2727 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2733 log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2734 for (count = 0; count < boundPortCount; count++)
2736 struct epoll_event ev;
2737 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2738 ev.events = EPOLLIN | EPOLLET;
2739 ev.data.fd = openSockfd[count];
2740 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2743 log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2744 printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2749 for (int t = 0; t != SERVERportCount; t++)
2751 struct epoll_event ev;
2752 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2753 ev.events = EPOLLIN | EPOLLET;
2754 ev.data.fd = me[t]->fd;
2755 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2758 log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2759 printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2765 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2766 for (count = 0; count < boundPortCount; count++)
2769 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2770 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2771 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2774 log(DEFAULT,"main: add listen ports to kqueue failed!");
2775 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2779 for (int t = 0; t != SERVERportCount; t++)
2784 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2785 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2786 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2789 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2790 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2798 log(DEFAULT,"Using standard select socket engine.");
2804 length = sizeof (client);
2805 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2809 struct kevent ke_list[33];
2813 struct epoll_event event[33];
2817 tvs.tv_usec = 10000L;
2820 tv.tv_usec = 10000L;
2824 tval.tv_usec = 10000L;
2826 int total_in_this_set = 0;
2827 int i = 0, v = 0, j = 0, cycle_iter = 0;
2828 bool expire_run = false;
2830 /* main loop, this never returns */
2833 #ifdef _POSIX_PRIORITY_SCHEDULING
2839 // we only read time() once per iteration rather than tons of times!
2845 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2846 // them in a list, then reap the list every second or so.
2847 if (((TIME % 5) == 0) && (!expire_run))
2849 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2851 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2852 ConfValue("link","name",i,Link_ServerName,&config_f);
2853 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2854 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2856 autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2857 if (a != autoconns.end())
2859 if (TIME > a->second)
2861 ConnectServer(Link_ServerName,NULL);
2862 a->second = TIME + atoi(Link_AConn);
2869 FOREACH_MOD OnBackgroundTimer(TIME);
2873 if ((TIME % 5) == 1)
2876 // fix by brain - this must be below any manipulation of the hashmap by modules
2877 user_hash::iterator count2 = clientlist.begin();
2880 i = epoll_wait(sep, event, 1, EP_DELAY);
2883 log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2884 for (int x = 0; x != SERVERportCount; x++)
2886 if ((me[x]) && (event[0].data.fd == me[x]->fd))
2891 ts.tv_nsec = 30000L;
2892 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2895 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2896 for (int x = 0; x != SERVERportCount; x++)
2898 if ((me[x]) && (ke.ident == me[x]->fd))
2903 FD_ZERO(&serverfds);
2904 for (int x = 0; x != SERVERportCount; x++)
2907 FD_SET(me[x]->fd, &serverfds);
2909 tvs.tv_usec = 30000L;
2911 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2914 for (int x = 0; x != SERVERportCount; x++)
2916 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2919 char remotehost[MAXBUF],resolved[MAXBUF];
2920 length = sizeof (client);
2921 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2922 if (incomingSockfd != -1)
2924 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2925 if(CleanAndResolve(resolved, remotehost) != TRUE)
2927 strlcpy(resolved,remotehost,MAXBUF);
2929 // add to this connections ircd_connector vector
2930 // *FIX* - we need the LOCAL port not the remote port in &client!
2931 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2937 std::deque<std::string> msgs;
2938 std::deque<std::string> sums;
2939 for (int x = 0; x < SERVERportCount; x++)
2942 me[x]->FlushWriteBuffers();
2945 while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2947 has_been_netsplit = false;
2948 for (int ctr = 0; ctr < msgs.size(); ctr++)
2950 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2951 strlcpy(tcp_sum,sums[ctr].c_str(),MAXBUF);
2952 log(DEBUG,"Processing: %s",tcp_msg);
2955 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2958 // during a netburst, send all data to all other linked servers
2959 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2961 if (is_uline(tcp_host))
2963 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2965 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2969 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2971 std::string msg = tcp_msg;
2972 FOREACH_MOD OnPacketReceive(msg,tcp_host);
2973 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2975 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2976 if (!me[x]->FindHost(tcp_host))
2978 log(DEBUG,"Connector gone, bailing!");
2982 sums.clear(); // we're done, clear the list for the next operation
2984 // theres been a netsplit, its unsafe to mess with the iterators!
2985 if (has_been_netsplit)
2987 log(DEBUG,"Iterator modified, bailing");
2993 while (count2 != clientlist.end())
2999 total_in_this_set = 0;
3001 user_hash::iterator xcount = count2;
3002 user_hash::iterator endingiter = count2;
3004 if (count2 == clientlist.end()) break;
3006 userrec* curr = NULL;
3009 curr = count2->second;
3011 if ((long)curr == -1)
3014 if ((curr) && (curr->fd != 0))
3016 #ifdef _POSIX_PRIORITY_SCHEDULING
3019 // assemble up to 64 sockets into an fd_set
3020 // to implement a pooling mechanism.
3022 // This should be up to 64x faster than the
3023 // old implementation.
3025 while (total_in_this_set < 1024)
3027 if (count2 != clientlist.end())
3029 curr = count2->second;
3030 if ((long)curr == -1)
3032 int currfd = curr->fd;
3033 // we don't check the state of remote users.
3034 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3036 curr->FlushWriteBuf();
3037 if (curr->GetWriteError() != "")
3039 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3040 kill_link(curr,curr->GetWriteError().c_str());
3044 FD_SET (curr->fd, &sfd);
3046 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3047 // their connection class.
3048 if ((TIME > curr->timeout) && (curr->registered != 7))
3050 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3051 kill_link(curr,"Registration timeout");
3054 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3056 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3057 curr->dns_done = true;
3059 FullConnectUser(curr);
3060 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3063 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3065 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3066 FullConnectUser(curr);
3067 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3070 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3072 if ((!curr->lastping) && (curr->registered == 7))
3074 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3075 kill_link(curr,"Ping timeout");
3078 Write(curr->fd,"PING :%s",ServerName);
3079 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3081 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3085 total_in_this_set++;
3089 endingiter = count2;
3090 count2 = xcount; // roll back to where we were
3092 // 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.
3093 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3095 if (cycle_iter > 20) while (count2 != clientlist.end())
3098 if (count2 != clientlist.end())
3100 curr = count2->second;
3101 if ((long)curr == -1)
3103 int currfd = curr->fd;
3104 // we don't check the state of remote users.
3105 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3108 curr->FlushWriteBuf();
3109 if (curr->GetWriteError() != "")
3111 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3112 kill_link(curr,curr->GetWriteError().c_str());
3116 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3117 // their connection class.
3118 if ((TIME > curr->timeout) && (curr->registered != 7))
3120 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3121 kill_link(curr,"Registration timeout");
3125 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3127 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3128 curr->dns_done = true;
3130 FullConnectUser(curr);
3131 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3134 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3136 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3137 FullConnectUser(curr);
3138 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3141 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3143 if ((!curr->lastping) && (curr->registered == 7))
3145 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3146 kill_link(curr,"Ping timeout");
3149 Write(curr->fd,"PING :%s",ServerName);
3150 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3152 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3159 // increment the counter right to the end of the list, as kqueue processes everything in one go
3164 int i = epoll_wait(ep, event, 1, 5);
3167 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3168 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3169 userrec* cu = fd_ref_table[event[0].data.fd];
3174 // for now, we only read 1 event. We could read soooo many more :)
3175 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3178 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3179 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3180 userrec* cu = fd_ref_table[ke.ident];
3184 tval.tv_usec = 1000L;
3185 selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3186 // now loop through all of the items in this pool if any are waiting
3187 if ((selectResult2 > 0) && (xcount != clientlist.end()))
3188 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3190 // SELECT: we have to iterate...
3191 if (count2a == clientlist.end())
3193 userrec* cu = count2a->second;
3196 #ifdef _POSIX_PRIORITY_SCHEDULING
3201 // EPOLL: We already know we have a valid FD. No checks needed.
3202 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3205 // KQUEUE: We already know we have a valid FD. No checks needed.
3206 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3209 // SELECT: We don't know if our FD is valid.
3210 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3213 log(DEBUG,"Data waiting on socket %d",cu->fd);
3216 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3219 result = cu->ReadData(data, 65535);
3221 else result = result2;
3222 log(DEBUG,"Read result: %d",result);
3225 statsRecv += result;
3226 // perform a check on the raw buffer as an array (not a string!) to remove
3227 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3228 // hopefully this should stop even more people whining about "Unknown command: *"
3229 for (int checker = 0; checker < result; checker++)
3231 if ((data[checker] == 0) || (data[checker] == 7))
3232 data[checker] = ' ';
3235 data[result] = '\0';
3236 userrec* current = cu;
3237 int currfd = current->fd;
3239 // add the data to the users buffer
3241 if (!current->AddBuffer(data))
3243 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3244 if (current->registered == 7)
3246 kill_link(current,"RecvQ exceeded");
3250 WriteOpers("*** Excess flood from %s",current->ip);
3251 log(DEFAULT,"Excess flood from: %s",current->ip);
3252 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3257 if (current->recvq.length() > NetBufferSize)
3259 if (current->registered == 7)
3261 kill_link(current,"RecvQ exceeded");
3265 WriteOpers("*** Excess flood from %s",current->ip);
3266 log(DEFAULT,"Excess flood from: %s",current->ip);
3267 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3272 // while there are complete lines to process...
3273 while (current->BufferIsReady())
3276 if (TIME > current->reset_due)
3278 current->reset_due = TIME + current->threshold;
3279 current->lines_in = 0;
3281 current->lines_in++;
3282 if (current->lines_in > current->flood)
3284 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3285 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3286 kill_link(current,"Excess flood");
3289 if ((floodlines > current->flood) && (current->flood != 0))
3291 if (current->registered == 7)
3293 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3294 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3295 kill_link(current,"Excess flood");
3299 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3304 char sanitized[MAXBUF];
3305 // use GetBuffer to copy single lines into the sanitized string
3306 std::string single_line = current->GetBuffer();
3307 current->bytes_in += single_line.length();
3309 if (single_line.length()>512)
3311 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3312 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3313 kill_link(current,"Excess flood");
3316 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3319 userrec* old_comp = fd_ref_table[currfd];
3320 // we're gonna re-scan to check if the nick is gone, after every
3321 // command - if it has, we're gonna bail
3322 process_buffer(sanitized,current);
3323 // look for the user's record in case it's changed... if theyve quit,
3324 // we cant do anything more with their buffer, so bail.
3325 // there used to be an ugly, slow loop here. Now we have a reference
3326 // table, life is much easier (and FASTER)
3327 userrec* new_comp = fd_ref_table[currfd];
3328 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3336 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3338 log(DEBUG,"killing: %s",cu->nick);
3339 kill_link(cu,strerror(errno));
3343 // result EAGAIN means nothing read
3344 if (result == EAGAIN)
3354 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3355 kill_link(cu,"Client exited");
3356 // must bail here? kill_link removes the hash, corrupting the iterator
3357 log(DEBUG,"Bailing from client exit");
3363 else if (result > 0)
3368 for (int q = 0; q < total_in_this_set; q++)
3374 #ifdef _POSIX_PRIORITY_SCHEDULING
3379 // set up select call
3380 for (count = 0; count < boundPortCount; count++)
3382 FD_SET (openSockfd[count], &selectFds);
3385 tv.tv_usec = 30000L;
3386 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3388 /* select is reporting a waiting socket. Poll them all to find out which */
3389 if (selectResult > 0)
3391 for (count = 0; count < boundPortCount; count++)
3393 if (FD_ISSET (openSockfd[count], &selectFds))
3398 ts.tv_nsec = 30000L;
3399 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3400 if (i > 0) for (j = 0; j < i; j++)
3402 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3403 // this isnt as efficient as it could be, we could create a reference table
3404 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3405 // number of listening ports on the average ircd is a small number (less than 20)
3406 // compared to the number of clients (possibly over 2000)
3407 for (count = 0; count < boundPortCount; count++)
3409 if (ke_list[j].ident == openSockfd[count])
3413 i = epoll_wait(lep, event, 32, EP_DELAY);
3414 if (i > 0) for (j = 0; j < i; j++)
3416 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3417 for (count = 0; count < boundPortCount; count++)
3419 if (event[j].data.fd == openSockfd[count])
3422 char target[MAXBUF], resolved[MAXBUF];
3423 length = sizeof (client);
3424 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3426 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3427 strlcpy (resolved, target, MAXBUF);
3429 if (incomingSockfd < 0)
3431 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3432 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3437 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3439 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3440 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3447 #ifdef _POSIX_PRIORITY_SCHEDULING
3453 close (incomingSockfd);