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 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1136 if (!strcmp(user->server,getservername.c_str()))
1137 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1141 if (iter != clientlist.end())
1143 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1145 fd_ref_table[user->fd] = NULL;
1146 clientlist.erase(iter);
1151 void kill_link_silent(userrec *user,const char* r)
1153 user_hash::iterator iter = clientlist.find(user->nick);
1155 char reason[MAXBUF];
1157 strncpy(reason,r,MAXBUF);
1159 if (strlen(reason)>MAXQUIT)
1161 reason[MAXQUIT-1] = '\0';
1164 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1165 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1166 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1168 user->FlushWriteBuf();
1170 if (user->registered == 7) {
1171 FOREACH_MOD OnUserQuit(user);
1172 WriteCommonExcept(user,"QUIT :%s",reason);
1174 // Q token must go to ALL servers!!!
1175 char buffer[MAXBUF];
1176 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1177 NetSendToAll(buffer);
1180 FOREACH_MOD OnUserDisconnect(user);
1184 FOREACH_MOD OnRawSocketClose(user->fd);
1187 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1188 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1191 log(DEBUG,"kqueue: Failed to remove user from queue!");
1195 struct epoll_event ev;
1196 ev.events = EPOLLIN | EPOLLET;
1197 ev.data.fd = user->fd;
1198 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1201 log(DEBUG,"epoll: List deletion failure!");
1204 user->CloseSocket();
1207 if (user->registered == 7) {
1208 purge_empty_chans(user);
1211 if (iter != clientlist.end())
1213 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1215 fd_ref_table[user->fd] = NULL;
1216 clientlist.erase(iter);
1222 int main(int argc, char** argv)
1226 log(DEBUG,"*** InspIRCd starting up!");
1227 if (!FileExists(CONFIG_FILE))
1229 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1230 log(DEFAULT,"main: no config");
1231 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1235 for (int i = 1; i < argc; i++)
1237 if (!strcmp(argv[i],"-nofork")) {
1240 if (!strcmp(argv[i],"-wait")) {
1243 if (!strcmp(argv[i],"-nolimit")) {
1248 strlcpy(MyExecutable,argv[0],MAXBUF);
1250 // initialize the lowercase mapping table
1251 for (int cn = 0; cn < 256; cn++)
1253 // lowercase the uppercase chars
1254 for (int cn = 65; cn < 91; cn++)
1255 lowermap[cn] = tolower(cn);
1256 // now replace the specific chars for scandanavian comparison
1257 lowermap['['] = '{';
1258 lowermap[']'] = '}';
1259 lowermap['\\'] = '|';
1261 if (InspIRCd(argv,argc) == ERROR)
1263 log(DEFAULT,"main: daemon function bailed");
1264 printf("ERROR: could not initialise. Shutting down.\n");
1271 template<typename T> inline string ConvToStr(const T &in)
1274 if (!(tmp << in)) return string();
1278 /* re-allocates a nick in the user_hash after they change nicknames,
1279 * returns a pointer to the new user as it may have moved */
1281 userrec* ReHashNick(char* Old, char* New)
1283 //user_hash::iterator newnick;
1284 user_hash::iterator oldnick = clientlist.find(Old);
1286 log(DEBUG,"ReHashNick: %s %s",Old,New);
1288 if (!strcasecmp(Old,New))
1290 log(DEBUG,"old nick is new nick, skipping");
1291 return oldnick->second;
1294 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1296 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1298 userrec* olduser = oldnick->second;
1299 clientlist[New] = olduser;
1300 clientlist.erase(oldnick);
1302 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1304 return clientlist[New];
1307 /* adds or updates an entry in the whowas list */
1308 void AddWhoWas(userrec* u)
1310 whowas_hash::iterator iter = whowas.find(u->nick);
1311 WhoWasUser *a = new WhoWasUser();
1312 strlcpy(a->nick,u->nick,NICKMAX);
1313 strlcpy(a->ident,u->ident,15);
1314 strlcpy(a->dhost,u->dhost,160);
1315 strlcpy(a->host,u->host,160);
1316 strlcpy(a->fullname,u->fullname,128);
1317 strlcpy(a->server,u->server,256);
1318 a->signon = u->signon;
1320 /* MAX_WHOWAS: max number of /WHOWAS items
1321 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1322 * can be replaced by a newer one
1325 if (iter == whowas.end())
1327 if (whowas.size() >= WHOWAS_MAX)
1329 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1331 // 3600 seconds in an hour ;)
1332 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1334 // delete the old one
1335 if (i->second) delete i->second;
1336 // replace with new one
1338 log(DEBUG,"added WHOWAS entry, purged an old record");
1342 // no space left and user doesnt exist. Don't leave ram in use!
1343 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1348 log(DEBUG,"added fresh WHOWAS entry");
1349 whowas[a->nick] = a;
1354 log(DEBUG,"updated WHOWAS entry");
1355 if (iter->second) delete iter->second;
1361 /* add a client connection to the sockets list */
1362 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1366 user_hash::iterator iter;
1368 tempnick = ConvToStr(socket) + "-unknown";
1369 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1371 iter = clientlist.find(tempnick);
1374 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1375 // using one as a registered connection. As theyre per fd, we can also safely assume
1376 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1377 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1378 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1379 // issue in earlier alphas/betas
1380 if (iter != clientlist.end())
1382 userrec* goner = iter->second;
1384 clientlist.erase(iter);
1388 * It is OK to access the value here this way since we know
1389 * it exists, we just created it above.
1391 * At NO other time should you access a value in a map or a
1392 * hash_map this way.
1394 clientlist[tempnick] = new userrec();
1396 NonBlocking(socket);
1397 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1399 clientlist[tempnick]->fd = socket;
1400 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1401 strncpy(clientlist[tempnick]->host, host,160);
1402 strncpy(clientlist[tempnick]->dhost, host,160);
1403 strncpy(clientlist[tempnick]->server, ServerName,256);
1404 strncpy(clientlist[tempnick]->ident, "unknown",15);
1405 clientlist[tempnick]->registered = 0;
1406 clientlist[tempnick]->signon = TIME+dns_timeout;
1407 clientlist[tempnick]->lastping = 1;
1408 clientlist[tempnick]->port = port;
1409 strncpy(clientlist[tempnick]->ip,ip,16);
1411 // set the registration timeout for this user
1412 unsigned long class_regtimeout = 90;
1413 int class_flood = 0;
1414 long class_threshold = 5;
1415 long class_sqmax = 262144; // 256kb
1416 long class_rqmax = 4096; // 4k
1418 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1420 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1422 class_regtimeout = (unsigned long)i->registration_timeout;
1423 class_flood = i->flood;
1424 clientlist[tempnick]->pingmax = i->pingtime;
1425 class_threshold = i->threshold;
1426 class_sqmax = i->sendqmax;
1427 class_rqmax = i->recvqmax;
1432 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1433 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1434 clientlist[tempnick]->flood = class_flood;
1435 clientlist[tempnick]->threshold = class_threshold;
1436 clientlist[tempnick]->sendqmax = class_sqmax;
1437 clientlist[tempnick]->recvqmax = class_rqmax;
1439 for (int i = 0; i < MAXCHANS; i++)
1441 clientlist[tempnick]->chans[i].channel = NULL;
1442 clientlist[tempnick]->chans[i].uc_modes = 0;
1445 if (clientlist.size() == MAXCLIENTS)
1447 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1451 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1452 // its a pretty big but for the moment valid assumption:
1453 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1454 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1455 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1456 // which for the time being is a physical impossibility (even the largest networks dont have more
1457 // than about 10,000 users on ONE server!)
1460 kill_link(clientlist[tempnick],"Server is full");
1465 char* e = matches_exception(ip);
1468 char* r = matches_zline(ip);
1471 char reason[MAXBUF];
1472 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1473 kill_link(clientlist[tempnick],reason);
1477 fd_ref_table[socket] = clientlist[tempnick];
1480 struct epoll_event ev;
1481 log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1482 ev.events = EPOLLIN | EPOLLET;
1483 ev.data.fd = socket;
1484 int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1487 log(DEBUG,"epoll: List insertion failure!");
1492 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1493 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1494 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1497 log(DEBUG,"kqueue: List insertion failure!");
1503 /* shows the message of the day, and any other on-logon stuff */
1504 void FullConnectUser(userrec* user)
1507 user->idle_lastmsg = TIME;
1508 log(DEBUG,"ConnectUser: %s",user->nick);
1510 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1512 kill_link(user,"Invalid password");
1517 kill_link(user,"Unauthorised connection");
1521 char match_against[MAXBUF];
1522 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1523 char* e = matches_exception(match_against);
1526 char* r = matches_gline(match_against);
1529 char reason[MAXBUF];
1530 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1531 kill_link_silent(user,reason);
1534 r = matches_kline(user->host);
1537 char reason[MAXBUF];
1538 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1539 kill_link_silent(user,reason);
1544 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1545 user->registered = 7;
1547 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1548 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1549 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1550 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1551 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1552 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1553 std::stringstream v;
1554 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1555 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1556 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1558 std::string data005 = v.str();
1559 FOREACH_MOD On005Numeric(data005);
1560 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1561 // so i'd better split it :)
1562 std::stringstream out(data005);
1563 std::string token = "";
1564 std::string line5 = "";
1565 int token_counter = 0;
1569 line5 = line5 + token + " ";
1571 if ((token_counter >= 13) || (out.eof() == true))
1573 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1580 char buffer[MAXBUF];
1581 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);
1582 NetSendToAll(buffer);
1584 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1585 FOREACH_MOD OnUserConnect(user);
1586 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1590 /* shows the message of the day, and any other on-logon stuff */
1591 void ConnectUser(userrec *user)
1593 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1594 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1596 FullConnectUser(user);
1600 std::string GetVersionString()
1602 char Revision[] = "$Revision$";
1603 char versiondata[MAXBUF];
1604 char *s1 = Revision;
1606 char *v2 = strtok_r(s1," ",&savept);
1608 v2 = strtok_r(s1," ",&savept);
1611 char socketengine[] = "kqueue";
1614 char socketengine[] = "select";
1617 char socketengine[] = "epoll";
1619 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1623 void handle_version(char **parameters, int pcnt, userrec *user)
1627 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1631 if (!strcmp(parameters[0],"*"))
1633 for (int j = 0; j < 32; j++)
1637 for (int x = 0; x < me[j]->connectors.size(); x++)
1639 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());
1645 if (match(ServerName,parameters[0]))
1647 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1650 bool displayed = false, found = false;
1651 for (int j = 0; j < 32; j++)
1655 for (int x = 0; x < me[j]->connectors.size(); x++)
1657 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1660 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1663 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1669 if ((!displayed) && (found))
1671 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1676 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1683 // calls a handler function for a command
1685 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1687 for (int i = 0; i < cmdlist.size(); i++)
1689 if (!strcasecmp(cmdlist[i].command,commandname))
1691 if (cmdlist[i].handler_function)
1693 if (pcnt>=cmdlist[i].min_params)
1695 if (strchr(user->modes,cmdlist[i].flags_needed))
1697 cmdlist[i].handler_function(parameters,pcnt,user);
1705 void DoSplitEveryone()
1707 bool go_again = true;
1711 for (int i = 0; i < 32; i++)
1715 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1717 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1720 j->CloseConnection();
1721 me[i]->connectors.erase(j);
1729 log(DEBUG,"Removed server. Will remove clients...");
1730 // iterate through the userlist and remove all users on this server.
1731 // because we're dealing with a mesh, we dont have to deal with anything
1732 // "down-route" from this server (nice huh)
1734 char reason[MAXBUF];
1738 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1740 if (strcasecmp(u->second->server,ServerName))
1742 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1743 kill_link(u->second,reason);
1749 has_been_netsplit = true;
1754 void force_nickchange(userrec* user,const char* newnick)
1761 FOREACH_RESULT(OnUserPreNick(user,newnick));
1764 kill_link(user,"Nickname collision");
1767 if (matches_qline(newnick))
1770 kill_link(user,"Nickname collision");
1778 strncpy(nick,newnick,MAXBUF);
1780 if (user->registered == 7)
1784 handle_nick(pars,1,user);
1790 int process_parameters(char **command_p,char *parameters)
1793 int q = strlen(parameters);
1796 /* no parameters, command_p invalid! */
1799 if (parameters[0] == ':')
1801 command_p[0] = parameters+1;
1806 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1808 /* only one parameter */
1809 command_p[0] = parameters;
1810 if (parameters[0] == ':')
1812 if (strchr(parameters,' ') != NULL)
1820 command_p[j++] = parameters;
1821 for (int i = 0; i <= q; i++)
1823 if (parameters[i] == ' ')
1825 command_p[j++] = parameters+i+1;
1826 parameters[i] = '\0';
1827 if (command_p[j-1][0] == ':')
1829 *command_p[j-1]++; /* remove dodgy ":" */
1831 /* parameter like this marks end of the sequence */
1835 return j; /* returns total number of items in the list */
1838 void process_command(userrec *user, char* cmd)
1842 char *command_p[127];
1843 char p[MAXBUF], temp[MAXBUF];
1844 int j, items, cmd_found;
1846 for (int i = 0; i < 127; i++)
1847 command_p[i] = NULL;
1862 int total_params = 0;
1865 for (int q = 0; q < strlen(cmd)-1; q++)
1867 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1870 // found a 'trailing', we dont count them after this.
1878 // another phidjit bug...
1879 if (total_params > 126)
1881 *(strchr(cmd,' ')) = '\0';
1882 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1886 strlcpy(temp,cmd,MAXBUF);
1888 std::string tmp = cmd;
1889 for (int i = 0; i <= MODCOUNT; i++)
1891 std::string oldtmp = tmp;
1892 modules[i]->OnServerRaw(tmp,true,user);
1895 log(DEBUG,"A Module changed the input string!");
1896 log(DEBUG,"New string: %s",tmp.c_str());
1897 log(DEBUG,"Old string: %s",oldtmp.c_str());
1901 strlcpy(cmd,tmp.c_str(),MAXBUF);
1902 strlcpy(temp,cmd,MAXBUF);
1904 if (!strchr(cmd,' '))
1906 /* no parameters, lets skip the formalities and not chop up
1908 log(DEBUG,"About to preprocess command with no params");
1910 command_p[0] = NULL;
1912 for (int i = 0; i <= strlen(cmd); i++)
1914 cmd[i] = toupper(cmd[i]);
1922 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1923 for (int i = 0; i < strlen(temp); i++)
1925 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1931 /* split the full string into a command plus parameters */
1935 if (strchr(cmd,' '))
1937 for (int i = 0; i <= strlen(cmd); i++)
1939 /* capitalise the command ONLY, leave params intact */
1940 cmd[i] = toupper(cmd[i]);
1941 /* are we nearly there yet?! :P */
1945 parameters = cmd+i+1;
1953 for (int i = 0; i <= strlen(cmd); i++)
1955 cmd[i] = toupper(cmd[i]);
1962 if (strlen(command)>MAXCOMMAND)
1964 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1968 for (int x = 0; x < strlen(command); x++)
1970 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1972 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1974 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1977 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1984 for (int i = 0; i != cmdlist.size(); i++)
1986 if (cmdlist[i].command[0])
1988 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1994 items = process_parameters(command_p,parameters);
1999 command_p[0] = NULL;
2005 command_p[0] = NULL;
2010 /* activity resets the ping pending timer */
2011 user->nping = TIME + user->pingmax;
2012 if ((items) < cmdlist[i].min_params)
2014 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2015 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2018 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2020 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2021 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2025 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2027 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2028 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2032 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2034 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2036 if ((!isnick(user->nick)) || (user->registered != 7))
2038 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2039 WriteServ(user->fd,"451 %s :You have not registered",command);
2043 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2047 mycmd = strtok_r(DisabledCommands," ",&savept2);
2050 if (!strcasecmp(mycmd,command))
2052 // command is disabled!
2053 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2056 mycmd = strtok_r(NULL," ",&savept2);
2061 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2063 if (cmdlist[i].handler_function)
2066 /* ikky /stats counters */
2069 cmdlist[i].use_count++;
2070 cmdlist[i].total_bytes+=strlen(temp);
2074 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2075 if (MOD_RESULT == 1) {
2079 /* WARNING: nothing may come after the
2080 * command handler call, as the handler
2081 * may free the user structure! */
2083 cmdlist[i].handler_function(command_p,items,user);
2089 WriteServ(user->fd,"451 %s :You have not registered",command);
2097 if ((!cmd_found) && (user))
2100 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2104 bool removecommands(const char* source)
2106 bool go_again = true;
2110 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2112 if (!strcmp(i->source,source))
2114 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2125 void process_buffer(const char* cmdbuf,userrec *user)
2129 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2135 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2142 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2144 strlcpy(cmd,cmdbuf,MAXBUF);
2149 int sl = strlen(cmd)-1;
2150 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2155 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2160 while (cmd[sl] == ' ') // strip trailing spaces
2170 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2172 if ((user) && (cmd))
2174 process_command(user,cmd);
2178 void DoSync(serverrec* serv, char* tcp_host)
2181 log(DEBUG,"Sending sync");
2182 // send start of sync marker: Y <timestamp>
2183 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2184 // except the ones its receiving it from.
2185 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2186 serv->SendPacket(data,tcp_host);
2187 // send users and channels
2189 NetSendMyRoutingTable();
2191 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2192 for (int j = 0; j < 32; j++)
2196 for (int k = 0; k < me[j]->connectors.size(); k++)
2198 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2200 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2201 serv->SendPacket(data,tcp_host);
2207 // send our version for the remote side to cache
2208 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2209 serv->SendPacket(data,tcp_host);
2211 // sync the users and channels, give the modules a look-in.
2212 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2214 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);
2215 serv->SendPacket(data,tcp_host);
2216 if (strchr(u->second->modes,'o'))
2218 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2219 serv->SendPacket(data,tcp_host);
2221 for (int i = 0; i <= MODCOUNT; i++)
2223 string_list l = modules[i]->OnUserSync(u->second);
2224 for (int j = 0; j < l.size(); j++)
2226 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2227 serv->SendPacket(data,tcp_host);
2230 char* chl = chlist(u->second,u->second);
2233 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2234 serv->SendPacket(data,tcp_host);
2237 // send channel modes, topics etc...
2238 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2240 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2241 serv->SendPacket(data,tcp_host);
2242 for (int i = 0; i <= MODCOUNT; i++)
2244 string_list l = modules[i]->OnChannelSync(c->second);
2245 for (int j = 0; j < l.size(); j++)
2247 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2248 serv->SendPacket(data,tcp_host);
2251 if (c->second->topic[0])
2253 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);
2254 serv->SendPacket(data,tcp_host);
2256 // send current banlist
2258 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2260 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2261 serv->SendPacket(data,tcp_host);
2264 // sync global zlines, glines, etc
2265 sync_xlines(serv,tcp_host);
2267 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2268 serv->SendPacket(data,tcp_host);
2269 log(DEBUG,"Sent sync");
2270 // ircd sends its serverlist after the end of sync here
2274 void NetSendMyRoutingTable()
2276 // send out a line saying what is reachable to us.
2277 // E.g. if A is linked to B C and D, send out:
2279 // if its only linked to B and D send out:
2281 // if it has no links, dont even send out the line at all.
2282 char buffer[MAXBUF];
2283 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2284 bool sendit = false;
2285 for (int i = 0; i < 32; i++)
2289 for (int j = 0; j < me[i]->connectors.size(); j++)
2291 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2293 strlcat(buffer," ",MAXBUF);
2294 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2301 NetSendToAll(buffer);
2305 void DoSplit(const char* params)
2307 bool go_again = true;
2311 for (int i = 0; i < 32; i++)
2315 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2317 if (!strcasecmp(j->GetServerName().c_str(),params))
2320 j->CloseConnection();
2321 me[i]->connectors.erase(j);
2329 log(DEBUG,"Removed server. Will remove clients...");
2330 // iterate through the userlist and remove all users on this server.
2331 // because we're dealing with a mesh, we dont have to deal with anything
2332 // "down-route" from this server (nice huh)
2334 char reason[MAXBUF];
2335 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2339 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2341 if (!strcasecmp(u->second->server,params))
2343 kill_link(u->second,reason);
2349 has_been_netsplit = true;
2352 // removes a server. Will NOT remove its users!
2354 void RemoveServer(const char* name)
2356 bool go_again = true;
2360 for (int i = 0; i < 32; i++)
2364 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2366 if (!strcasecmp(j->GetServerName().c_str(),name))
2369 j->CloseConnection();
2370 me[i]->connectors.erase(j);
2381 char MODERR[MAXBUF];
2388 void erase_factory(int j)
2391 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2396 factory.push_back(NULL);
2403 void erase_module(int j)
2406 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2412 modules.push_back(NULL);
2418 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2422 module_names.erase(v);
2430 bool UnloadModule(const char* filename)
2432 std::string filename_str = filename;
2433 for (int j = 0; j != module_names.size(); j++)
2435 if (module_names[j] == filename_str)
2437 if (modules[j]->GetVersion().Flags & VF_STATIC)
2439 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2440 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2444 log(DEBUG,"Deleting module...");
2446 log(DEBUG,"Erasing module entry...");
2448 log(DEBUG,"Removing dependent commands...");
2449 removecommands(filename);
2450 log(DEFAULT,"Module %s unloaded",filename);
2455 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2456 snprintf(MODERR,MAXBUF,"Module not loaded");
2460 bool LoadModule(const char* filename)
2462 char modfile[MAXBUF];
2464 snprintf(modfile,MAXBUF,"%s",filename);
2466 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2468 std::string filename_str = filename;
2470 if (!DirValid(modfile))
2472 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2473 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2477 log(DEBUG,"Loading module: %s",modfile);
2479 if (FileExists(modfile))
2482 for (int j = 0; j < module_names.size(); j++)
2484 if (module_names[j] == filename_str)
2486 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2487 snprintf(MODERR,MAXBUF,"Module already loaded");
2491 ircd_module* a = new ircd_module(modfile);
2492 factory[MODCOUNT+1] = a;
2493 if (factory[MODCOUNT+1]->LastError())
2495 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2496 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2500 if (factory[MODCOUNT+1]->factory)
2502 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2503 modules[MODCOUNT+1] = m;
2504 /* save the module and the module's classfactory, if
2505 * this isnt done, random crashes can occur :/ */
2506 module_names.push_back(filename);
2510 log(DEFAULT,"Unable to load %s",modfile);
2511 snprintf(MODERR,MAXBUF,"Factory function failed!");
2518 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2519 snprintf(MODERR,MAXBUF,"Module file could not be found");
2528 bool GotServer(std::string name)
2530 for (int j = 0; j < 32; j++)
2534 for (int k = 0; k < me[j]->connectors.size(); k++)
2536 if (name == me[j]->connectors[k].GetServerName())
2547 int InspIRCd(char** argv, int argc)
2549 struct sockaddr_in client,server;
2550 char addrs[MAXBUF][255];
2551 int incomingSockfd, result = TRUE;
2554 int selectResult = 0, selectResult2 = 0;
2555 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2559 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2560 log_file = fopen(logpath.c_str(),"a+");
2563 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2568 printf("Logging to ircd.log...\n");
2570 printf("Logging to %s...\n",logpath.c_str());
2573 log(DEFAULT,"$Id$");
2576 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2578 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2580 SetupCommandTable();
2581 log(DEBUG,"InspIRCd: startup: default command table set up");
2583 ReadConfig(true,NULL);
2586 printf("WARNING: %s\n\n",DieValue);
2587 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2590 log(DEBUG,"InspIRCd: startup: read config");
2592 int clientportcount = 0, serverportcount = 0;
2594 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2596 ConfValue("bind","port",count,configToken,&config_f);
2597 ConfValue("bind","address",count,Addr,&config_f);
2598 ConfValue("bind","type",count,Type,&config_f);
2599 if (!strcmp(Type,"servers"))
2601 char Default[MAXBUF];
2602 strcpy(Default,"no");
2603 ConfValue("bind","default",count,Default,&config_f);
2604 if (strchr(Default,'y'))
2606 defaultRoute = serverportcount;
2607 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2609 me[serverportcount] = new serverrec(ServerName,100L,false);
2610 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2612 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2613 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2622 ports[clientportcount] = atoi(configToken);
2623 strlcpy(addrs[clientportcount],Addr,256);
2626 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2628 portCount = clientportcount;
2629 SERVERportCount = serverportcount;
2631 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2632 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2636 /* BugFix By Craig! :p */
2638 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2640 ConfValue("module","name",count,configToken,&config_f);
2641 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2642 if (!LoadModule(configToken))
2644 log(DEFAULT,"Exiting due to a module loader error.");
2645 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2649 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2651 startup_time = time(NULL);
2654 ConfValue("pid","file",0,PID,&config_f);
2655 // write once here, to try it out and make sure its ok
2658 /* setup select call */
2660 FD_ZERO(&selectFds);
2662 log(DEBUG,"InspIRCd: startup: zero selects");
2663 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2665 for (count = 0; count < portCount; count++)
2667 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2669 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2672 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2674 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2676 else /* well we at least bound to one socket so we'll continue */
2682 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2684 /* if we didn't bind to anything then abort */
2685 if (boundPortCount == 0)
2687 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2688 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2693 printf("\nInspIRCd is now running!\n");
2697 log(VERBOSE,"Not forking as -nofork was specified");
2701 if (DaemonSeed() == ERROR)
2703 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2704 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2709 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2714 if ((kq == -1) || (lkq == -1) || (skq == -1))
2716 log(DEFAULT,"main: kqueue() failed!");
2717 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2723 ep = epoll_create(MAXCLIENTS);
2724 lep = epoll_create(32);
2725 sep = epoll_create(128);
2726 if ((ep == -1) || (lep == -1) || (sep == -1))
2728 log(DEFAULT,"main: epoll_create() failed!");
2729 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2735 log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2736 for (count = 0; count < boundPortCount; count++)
2738 struct epoll_event ev;
2739 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2740 ev.events = EPOLLIN | EPOLLET;
2741 ev.data.fd = openSockfd[count];
2742 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2745 log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2746 printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2751 for (int t = 0; t != SERVERportCount; t++)
2753 struct epoll_event ev;
2754 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2755 ev.events = EPOLLIN | EPOLLET;
2756 ev.data.fd = me[t]->fd;
2757 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2760 log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2761 printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2767 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2768 for (count = 0; count < boundPortCount; count++)
2771 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2772 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2773 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2776 log(DEFAULT,"main: add listen ports to kqueue failed!");
2777 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2781 for (int t = 0; t != SERVERportCount; t++)
2786 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2787 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2788 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2791 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2792 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2800 log(DEFAULT,"Using standard select socket engine.");
2806 length = sizeof (client);
2807 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2811 struct kevent ke_list[33];
2815 struct epoll_event event[33];
2819 tvs.tv_usec = 10000L;
2822 tv.tv_usec = 10000L;
2826 tval.tv_usec = 10000L;
2828 int total_in_this_set = 0;
2829 int i = 0, v = 0, j = 0, cycle_iter = 0;
2830 bool expire_run = false;
2832 /* main loop, this never returns */
2835 #ifdef _POSIX_PRIORITY_SCHEDULING
2841 // we only read time() once per iteration rather than tons of times!
2847 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2848 // them in a list, then reap the list every second or so.
2849 if (((TIME % 5) == 0) && (!expire_run))
2851 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2853 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2854 ConfValue("link","name",i,Link_ServerName,&config_f);
2855 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2856 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2858 autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2859 if (a != autoconns.end())
2861 if (TIME > a->second)
2863 ConnectServer(Link_ServerName,NULL);
2864 a->second = TIME + atoi(Link_AConn);
2871 FOREACH_MOD OnBackgroundTimer(TIME);
2875 if ((TIME % 5) == 1)
2878 // fix by brain - this must be below any manipulation of the hashmap by modules
2879 user_hash::iterator count2 = clientlist.begin();
2882 i = epoll_wait(sep, event, 1, EP_DELAY);
2885 log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2886 for (int x = 0; x != SERVERportCount; x++)
2888 if ((me[x]) && (event[0].data.fd == me[x]->fd))
2893 ts.tv_nsec = 30000L;
2894 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2897 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2898 for (int x = 0; x != SERVERportCount; x++)
2900 if ((me[x]) && (ke.ident == me[x]->fd))
2905 FD_ZERO(&serverfds);
2906 for (int x = 0; x != SERVERportCount; x++)
2909 FD_SET(me[x]->fd, &serverfds);
2911 tvs.tv_usec = 30000L;
2913 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2916 for (int x = 0; x != SERVERportCount; x++)
2918 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2921 char remotehost[MAXBUF],resolved[MAXBUF];
2922 length = sizeof (client);
2923 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2924 if (incomingSockfd != -1)
2926 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2927 if(CleanAndResolve(resolved, remotehost) != TRUE)
2929 strlcpy(resolved,remotehost,MAXBUF);
2931 // add to this connections ircd_connector vector
2932 // *FIX* - we need the LOCAL port not the remote port in &client!
2933 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2939 std::deque<std::string> msgs;
2940 std::deque<std::string> sums;
2941 for (int x = 0; x < SERVERportCount; x++)
2944 me[x]->FlushWriteBuffers();
2947 while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2949 has_been_netsplit = false;
2950 for (int ctr = 0; ctr < msgs.size(); ctr++)
2952 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2953 strlcpy(tcp_sum,sums[ctr].c_str(),MAXBUF);
2954 log(DEBUG,"Processing: %s",tcp_msg);
2957 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2960 // during a netburst, send all data to all other linked servers
2961 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2963 if (is_uline(tcp_host))
2965 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2967 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2971 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2973 std::string msg = tcp_msg;
2974 FOREACH_MOD OnPacketReceive(msg,tcp_host);
2975 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2977 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2978 if (!me[x]->FindHost(tcp_host))
2980 log(DEBUG,"Connector gone, bailing!");
2988 while (count2 != clientlist.end())
2994 total_in_this_set = 0;
2996 user_hash::iterator xcount = count2;
2997 user_hash::iterator endingiter = count2;
2999 if (count2 == clientlist.end()) break;
3001 userrec* curr = NULL;
3004 curr = count2->second;
3006 if ((long)curr == -1)
3009 if ((curr) && (curr->fd != 0))
3011 #ifdef _POSIX_PRIORITY_SCHEDULING
3014 // assemble up to 64 sockets into an fd_set
3015 // to implement a pooling mechanism.
3017 // This should be up to 64x faster than the
3018 // old implementation.
3020 while (total_in_this_set < 1024)
3022 if (count2 != clientlist.end())
3024 curr = count2->second;
3025 if ((long)curr == -1)
3027 int currfd = curr->fd;
3028 // we don't check the state of remote users.
3029 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3031 curr->FlushWriteBuf();
3032 if (curr->GetWriteError() != "")
3034 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3035 kill_link(curr,curr->GetWriteError().c_str());
3039 FD_SET (curr->fd, &sfd);
3041 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3042 // their connection class.
3043 if ((TIME > curr->timeout) && (curr->registered != 7))
3045 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3046 kill_link(curr,"Registration timeout");
3049 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3051 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3052 curr->dns_done = true;
3054 FullConnectUser(curr);
3055 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3058 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3060 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3061 FullConnectUser(curr);
3062 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3065 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3067 if ((!curr->lastping) && (curr->registered == 7))
3069 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3070 kill_link(curr,"Ping timeout");
3073 Write(curr->fd,"PING :%s",ServerName);
3074 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3076 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3080 total_in_this_set++;
3084 endingiter = count2;
3085 count2 = xcount; // roll back to where we were
3087 // 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.
3088 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3090 if (cycle_iter > 20) while (count2 != clientlist.end())
3093 if (count2 != clientlist.end())
3095 curr = count2->second;
3096 if ((long)curr == -1)
3098 int currfd = curr->fd;
3099 // we don't check the state of remote users.
3100 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3103 curr->FlushWriteBuf();
3104 if (curr->GetWriteError() != "")
3106 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3107 kill_link(curr,curr->GetWriteError().c_str());
3111 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3112 // their connection class.
3113 if ((TIME > curr->timeout) && (curr->registered != 7))
3115 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3116 kill_link(curr,"Registration timeout");
3120 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3122 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3123 curr->dns_done = true;
3125 FullConnectUser(curr);
3126 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3129 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3131 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3132 FullConnectUser(curr);
3133 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3136 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3138 if ((!curr->lastping) && (curr->registered == 7))
3140 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3141 kill_link(curr,"Ping timeout");
3144 Write(curr->fd,"PING :%s",ServerName);
3145 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3147 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3154 // increment the counter right to the end of the list, as kqueue processes everything in one go
3159 int i = epoll_wait(ep, event, 1, 5);
3162 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3163 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3164 userrec* cu = fd_ref_table[event[0].data.fd];
3169 // for now, we only read 1 event. We could read soooo many more :)
3170 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3173 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3174 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3175 userrec* cu = fd_ref_table[ke.ident];
3179 tval.tv_usec = 1000L;
3180 selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3181 // now loop through all of the items in this pool if any are waiting
3182 if ((selectResult2 > 0) && (xcount != clientlist.end()))
3183 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3185 // SELECT: we have to iterate...
3186 if (count2a == clientlist.end())
3188 userrec* cu = count2a->second;
3191 #ifdef _POSIX_PRIORITY_SCHEDULING
3196 // EPOLL: We already know we have a valid FD. No checks needed.
3197 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3200 // KQUEUE: We already know we have a valid FD. No checks needed.
3201 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3204 // SELECT: We don't know if our FD is valid.
3205 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3208 log(DEBUG,"Data waiting on socket %d",cu->fd);
3211 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3214 result = cu->ReadData(data, 65535);
3216 else result = result2;
3217 log(DEBUG,"Read result: %d",result);
3220 statsRecv += result;
3221 // perform a check on the raw buffer as an array (not a string!) to remove
3222 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3223 // hopefully this should stop even more people whining about "Unknown command: *"
3224 for (int checker = 0; checker < result; checker++)
3226 if ((data[checker] == 0) || (data[checker] == 7))
3227 data[checker] = ' ';
3230 data[result] = '\0';
3231 userrec* current = cu;
3232 int currfd = current->fd;
3234 // add the data to the users buffer
3236 if (!current->AddBuffer(data))
3238 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3239 if (current->registered == 7)
3241 kill_link(current,"RecvQ exceeded");
3245 WriteOpers("*** Excess flood from %s",current->ip);
3246 log(DEFAULT,"Excess flood from: %s",current->ip);
3247 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3252 if (current->recvq.length() > NetBufferSize)
3254 if (current->registered == 7)
3256 kill_link(current,"RecvQ exceeded");
3260 WriteOpers("*** Excess flood from %s",current->ip);
3261 log(DEFAULT,"Excess flood from: %s",current->ip);
3262 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3267 // while there are complete lines to process...
3268 while (current->BufferIsReady())
3271 if (TIME > current->reset_due)
3273 current->reset_due = TIME + current->threshold;
3274 current->lines_in = 0;
3276 current->lines_in++;
3277 if (current->lines_in > current->flood)
3279 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3280 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3281 kill_link(current,"Excess flood");
3284 if ((floodlines > current->flood) && (current->flood != 0))
3286 if (current->registered == 7)
3288 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3289 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3290 kill_link(current,"Excess flood");
3294 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3299 char sanitized[MAXBUF];
3300 // use GetBuffer to copy single lines into the sanitized string
3301 std::string single_line = current->GetBuffer();
3302 current->bytes_in += single_line.length();
3304 if (single_line.length()>512)
3306 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3307 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3308 kill_link(current,"Excess flood");
3311 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3314 userrec* old_comp = fd_ref_table[currfd];
3315 // we're gonna re-scan to check if the nick is gone, after every
3316 // command - if it has, we're gonna bail
3317 process_buffer(sanitized,current);
3318 // look for the user's record in case it's changed... if theyve quit,
3319 // we cant do anything more with their buffer, so bail.
3320 // there used to be an ugly, slow loop here. Now we have a reference
3321 // table, life is much easier (and FASTER)
3322 userrec* new_comp = fd_ref_table[currfd];
3323 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3331 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3333 log(DEBUG,"killing: %s",cu->nick);
3334 kill_link(cu,strerror(errno));
3338 // result EAGAIN means nothing read
3339 if (result == EAGAIN)
3349 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3350 kill_link(cu,"Client exited");
3351 // must bail here? kill_link removes the hash, corrupting the iterator
3352 log(DEBUG,"Bailing from client exit");
3358 else if (result > 0)
3363 for (int q = 0; q < total_in_this_set; q++)
3369 #ifdef _POSIX_PRIORITY_SCHEDULING
3374 // set up select call
3375 for (count = 0; count < boundPortCount; count++)
3377 FD_SET (openSockfd[count], &selectFds);
3380 tv.tv_usec = 30000L;
3381 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3383 /* select is reporting a waiting socket. Poll them all to find out which */
3384 if (selectResult > 0)
3386 for (count = 0; count < boundPortCount; count++)
3388 if (FD_ISSET (openSockfd[count], &selectFds))
3393 ts.tv_nsec = 30000L;
3394 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3395 if (i > 0) for (j = 0; j < i; j++)
3397 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3398 // this isnt as efficient as it could be, we could create a reference table
3399 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3400 // number of listening ports on the average ircd is a small number (less than 20)
3401 // compared to the number of clients (possibly over 2000)
3402 for (count = 0; count < boundPortCount; count++)
3404 if (ke_list[j].ident == openSockfd[count])
3408 i = epoll_wait(lep, event, 32, EP_DELAY);
3409 if (i > 0) for (j = 0; j < i; j++)
3411 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3412 for (count = 0; count < boundPortCount; count++)
3414 if (event[j].data.fd == openSockfd[count])
3417 char target[MAXBUF], resolved[MAXBUF];
3418 length = sizeof (client);
3419 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3421 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3422 strlcpy (resolved, target, MAXBUF);
3424 if (incomingSockfd < 0)
3426 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3427 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3432 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3434 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3435 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3442 #ifdef _POSIX_PRIORITY_SCHEDULING
3448 close (incomingSockfd);