1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
21 #include "inspircd_config.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
32 #include <sys/types.h>
33 #include <sys/event.h>
38 #include <sys/epoll.h>
45 #include <ext/hash_map>
54 #include "connection.h"
66 #include "inspstring.h"
68 #include "helperfuncs.h"
71 int LogLevel = DEFAULT;
72 char ServerName[MAXBUF];
74 char ServerDesc[MAXBUF];
75 char AdminName[MAXBUF];
76 char AdminEmail[MAXBUF];
77 char AdminNick[MAXBUF];
79 char restartpass[MAXBUF];
83 char PrefixQuit[MAXBUF];
84 char DieValue[MAXBUF];
85 char DNSServer[MAXBUF];
87 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
88 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
90 time_t startup_time = time(NULL);
91 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
92 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
93 unsigned int SoftLimit = MAXCLIENTS;
94 extern int MaxWhoResults;
98 char DisabledCommands[MAXBUF];
100 bool AllowHalfop = true;
101 bool AllowProtect = true;
102 bool AllowFounder = true;
104 extern std::vector<Module*> modules;
105 std::vector<std::string> module_names;
106 extern std::vector<ircd_module*> factory;
109 int openSockfd[MAXSOCKS];
111 bool unlimitcore = false;
113 time_t TIME = time(NULL), OLDTIME = time(NULL);
123 bool has_been_netsplit = false;
124 extern std::vector<std::string> include_stack;
126 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
127 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
128 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
129 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
130 typedef std::deque<command_t> command_table;
131 typedef std::map<std::string,time_t> autoconnects;
132 typedef std::vector<std::string> servernamelist;
134 // This table references users by file descriptor.
135 // its an array to make it VERY fast, as all lookups are referenced
136 // by an integer, meaning there is no need for a scan/search operation.
137 userrec* fd_ref_table[65536];
139 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
145 user_hash clientlist;
148 command_table cmdlist;
149 autoconnects autoconns;
155 servernamelist servernames;
157 struct linger linger = { 0 };
158 char MyExecutable[1024];
159 int boundPortCount = 0;
160 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
161 int defaultRoute = 0;
162 char ModPath[MAXBUF];
166 int has_channel(userrec *u, chanrec *c);
167 int usercount(chanrec *c);
168 int usercount_i(chanrec *c);
169 char* Passwd(userrec *user);
170 bool IsDenied(userrec *user);
171 void AddWhoWas(userrec* u);
173 std::vector<long> auth_cookies;
174 std::stringstream config_f(stringstream::in | stringstream::out);
176 std::vector<userrec*> all_opers;
180 void AddOper(userrec* user)
182 log(DEBUG,"Oper added to optimization list");
183 all_opers.push_back(user);
186 void AddServerName(std::string servername)
188 log(DEBUG,"Adding server name: %s",servername.c_str());
189 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
191 if (*a == servername)
194 servernames.push_back(servername);
197 const char* FindServerNamePtr(std::string servername)
199 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
201 if (*a == servername)
207 void DeleteOper(userrec* user)
209 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
213 log(DEBUG,"Oper removed from optimization list");
220 std::string GetRevision()
222 char Revision[] = "$Revision$";
225 char *v2 = strtok_r(s1," ",&savept);
227 v2 = strtok_r(s1," ",&savept);
229 return std::string(v2);
233 std::string getservername()
238 std::string getserverdesc()
243 std::string getnetworkname()
248 std::string getadminname()
253 std::string getadminemail()
258 std::string getadminnick()
263 void ReadConfig(bool bail, userrec* user)
265 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
266 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
268 std::stringstream errstr;
269 include_stack.clear();
271 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
274 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
277 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
285 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
286 while (!errstr.eof())
288 errstr.getline(dataline,1024);
289 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
294 WriteOpers("There were errors in the configuration file:",user->nick);
295 while (!errstr.eof())
297 errstr.getline(dataline,1024);
298 WriteOpers(dataline);
305 ConfValue("server","name",0,ServerName,&config_f);
306 ConfValue("server","description",0,ServerDesc,&config_f);
307 ConfValue("server","network",0,Network,&config_f);
308 ConfValue("admin","name",0,AdminName,&config_f);
309 ConfValue("admin","email",0,AdminEmail,&config_f);
310 ConfValue("admin","nick",0,AdminNick,&config_f);
311 ConfValue("files","motd",0,motd,&config_f);
312 ConfValue("files","rules",0,rules,&config_f);
313 ConfValue("power","diepass",0,diepass,&config_f);
314 ConfValue("power","pause",0,pauseval,&config_f);
315 ConfValue("power","restartpass",0,restartpass,&config_f);
316 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
317 ConfValue("die","value",0,DieValue,&config_f);
318 ConfValue("options","loglevel",0,dbg,&config_f);
319 ConfValue("options","netbuffersize",0,NB,&config_f);
320 ConfValue("options","maxwho",0,MW,&config_f);
321 ConfValue("options","allowhalfop",0,AH,&config_f);
322 ConfValue("options","allowprotect",0,AP,&config_f);
323 ConfValue("options","allowfounder",0,AF,&config_f);
324 ConfValue("dns","server",0,DNSServer,&config_f);
325 ConfValue("dns","timeout",0,DNT,&config_f);
326 ConfValue("options","moduledir",0,ModPath,&config_f);
327 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
328 ConfValue("options","somaxconn",0,MCON,&config_f);
329 ConfValue("options","softlimit",0,SLIMT,&config_f);
331 SoftLimit = atoi(SLIMT);
332 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
334 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
335 SoftLimit = MAXCLIENTS;
337 MaxConn = atoi(MCON);
338 if (MaxConn > SOMAXCONN)
339 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
340 NetBufferSize = atoi(NB);
341 MaxWhoResults = atoi(MW);
342 dns_timeout = atoi(DNT);
348 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
350 strlcpy(ModPath,MOD_PATH,MAXBUF);
351 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
352 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
353 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
354 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
356 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
357 NetBufferSize = 10240;
359 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
361 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
364 if (!strcmp(dbg,"debug"))
366 if (!strcmp(dbg,"verbose"))
368 if (!strcmp(dbg,"default"))
370 if (!strcmp(dbg,"sparse"))
372 if (!strcmp(dbg,"none"))
375 log(DEFAULT,"Reading message of the day...");
376 readfile(RULES,rules);
377 log(DEFAULT,"Reading connect classes...");
379 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
382 ConfValue("connect","allow",i,Value,&config_f);
383 ConfValue("connect","timeout",i,timeout,&config_f);
384 ConfValue("connect","flood",i,flood,&config_f);
385 ConfValue("connect","pingfreq",i,pfreq,&config_f);
386 ConfValue("connect","threshold",i,thold,&config_f);
387 ConfValue("connect","sendq",i,sqmax,&config_f);
388 ConfValue("connect","recvq",i,rqmax,&config_f);
391 strlcpy(c.host,Value,MAXBUF);
393 strlcpy(Value,"",MAXBUF);
394 ConfValue("connect","password",i,Value,&config_f);
395 strlcpy(c.pass,Value,MAXBUF);
396 c.registration_timeout = 90; // default is 2 minutes
398 c.flood = atoi(flood);
400 c.sendqmax = 262144; // 256k
401 c.recvqmax = 4096; // 4k
404 c.threshold = atoi(thold);
408 c.sendqmax = atoi(sqmax);
412 c.recvqmax = atoi(rqmax);
416 c.registration_timeout = atoi(timeout);
420 c.pingtime = atoi(pfreq);
422 Classes.push_back(c);
423 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);
427 ConfValue("connect","deny",i,Value,&config_f);
428 strlcpy(c.host,Value,MAXBUF);
430 Classes.push_back(c);
431 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
435 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
436 read_xline_defaults();
437 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
441 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
443 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
444 ConfValue("link","name",i,Link_ServerName,&config_f);
445 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
446 if (strcmp(Link_AConn,""))
448 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
453 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
456 log(DEFAULT,"Adding and removing modules due to rehash...");
458 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
460 // store the old module names
461 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
463 old_module_names.push_back(*t);
466 // get the new module names
467 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
469 ConfValue("module","name",count2,Value,&config_f);
470 new_module_names.push_back(Value);
473 // now create a list of new modules that are due to be loaded
474 // and a seperate list of modules which are due to be unloaded
475 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
478 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
484 added_modules.push_back(*_new);
486 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
489 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
495 removed_modules.push_back(*oldm);
497 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
499 int rem = 0, add = 0;
500 if (!removed_modules.empty())
501 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
503 if (UnloadModule(removing->c_str()))
505 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
506 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
511 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
514 if (!added_modules.empty())
515 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
517 if (LoadModule(adding->c_str()))
519 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
520 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
525 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
528 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());
533 /* add a channel to a user, creating the record for it if needed and linking
534 * it to the user record */
536 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
538 if ((!user) || (!cn))
540 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
548 strncpy(cname,cn,MAXBUF);
550 // we MUST declare this wherever we use FOREACH_RESULT
553 if (strlen(cname) > CHANMAX)
555 cname[CHANMAX] = '\0';
558 log(DEBUG,"add_channel: %s %s",user->nick,cname);
560 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
562 return NULL; // already on the channel!
566 if (!FindChan(cname))
569 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
570 if (MOD_RESULT == 1) {
574 /* create a new one */
575 log(DEBUG,"add_channel: creating: %s",cname);
577 chanlist[cname] = new chanrec();
579 strlcpy(chanlist[cname]->name, cname,CHANMAX);
580 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
581 chanlist[cname]->created = TIME;
582 strcpy(chanlist[cname]->topic, "");
583 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
584 chanlist[cname]->topicset = 0;
585 Ptr = chanlist[cname];
586 log(DEBUG,"add_channel: created: %s",cname);
587 /* set created to 2 to indicate user
588 * is the first in the channel
589 * and should be given ops */
595 /* channel exists, just fish out a pointer to its struct */
596 Ptr = FindChan(cname);
599 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
601 // the override flag allows us to bypass channel modes
602 // and bans (used by servers)
603 if ((!override) || (!strcasecmp(user->server,ServerName)))
605 log(DEBUG,"Not overriding...");
607 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
608 if (MOD_RESULT == 1) {
611 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
615 log(DEBUG,"add_channel: checking key, invite, etc");
617 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
622 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
625 log(DEBUG,"add_channel: no key given in JOIN");
626 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
631 if (strcasecmp(key,Ptr->key))
633 log(DEBUG,"add_channel: bad key given in JOIN");
634 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
639 log(DEBUG,"add_channel: no key");
642 FOREACH_RESULT(OnCheckInvite(user, Ptr));
645 if (Ptr->binarymodes & CM_INVITEONLY)
647 log(DEBUG,"add_channel: channel is +i");
648 if (user->IsInvited(Ptr->name))
650 /* user was invited to channel */
651 /* there may be an optional channel NOTICE here */
655 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
659 log(DEBUG,"add_channel: channel is not +i");
662 FOREACH_RESULT(OnCheckLimit(user, Ptr));
667 if (usercount(Ptr) >= Ptr->limit)
669 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
674 log(DEBUG,"add_channel: about to walk banlist");
676 FOREACH_RESULT(OnCheckBan(user, Ptr));
679 /* check user against the channel banlist */
682 if (Ptr->bans.size())
684 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
686 if (match(user->GetFullHost(),i->data))
688 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
694 log(DEBUG,"add_channel: bans checked");
702 user->RemoveInvite(Ptr->name);
705 log(DEBUG,"add_channel: invites removed");
710 log(DEBUG,"Overridden checks");
718 log(DEBUG,"Passed channel checks");
720 for (int index =0; index != MAXCHANS; index++)
722 log(DEBUG,"Check location %d",index);
723 if (user->chans[index].channel == NULL)
725 log(DEBUG,"Adding into their channel list at location %d",index);
729 /* first user in is given ops */
730 user->chans[index].uc_modes = UCMODE_OP;
734 user->chans[index].uc_modes = 0;
736 user->chans[index].channel = Ptr;
737 Ptr->AddUser((char*)user);
738 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
740 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
742 // use the stamdard J token with no privilages.
746 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
750 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
752 NetSendToAll(buffer);
755 log(DEBUG,"Sent JOIN to client");
759 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
760 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
763 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
764 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
765 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
766 FOREACH_MOD OnUserJoin(user,Ptr);
770 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
771 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
775 /* remove a channel from a users record, and remove the record from memory
776 * if the channel has become empty */
778 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
780 if ((!user) || (!cname))
782 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
788 if ((!cname) || (!user))
793 Ptr = FindChan(cname);
800 FOREACH_MOD OnUserPart(user,Ptr);
801 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
803 for (int i =0; i != MAXCHANS; i++)
805 /* zap it from the channel list of the user */
806 if (user->chans[i].channel == Ptr)
810 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
815 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
816 NetSendToAll(buffer);
826 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
827 NetSendToAll(buffer);
830 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
832 user->chans[i].uc_modes = 0;
833 user->chans[i].channel = NULL;
834 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
839 Ptr->DelUser((char*)user);
841 /* if there are no users left on the channel */
844 chan_hash::iterator iter = chanlist.find(Ptr->name);
846 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
848 /* kill the record */
849 if (iter != chanlist.end())
851 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
853 chanlist.erase(iter);
861 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
863 if ((!src) || (!user) || (!Ptr) || (!reason))
865 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
869 if ((!Ptr) || (!user) || (!src))
874 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
876 if (!has_channel(user,Ptr))
878 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
883 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
884 if (MOD_RESULT == ACR_DENY)
887 if (MOD_RESULT == ACR_DEFAULT)
889 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
891 if (cstatus(src,Ptr) == STATUS_HOP)
893 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
897 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
905 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
909 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
911 for (int i =0; i != MAXCHANS; i++)
913 /* zap it from the channel list of the user */
914 if (user->chans[i].channel)
915 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
917 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
918 user->chans[i].uc_modes = 0;
919 user->chans[i].channel = NULL;
920 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
925 Ptr->DelUser((char*)user);
927 /* if there are no users left on the channel */
930 chan_hash::iterator iter = chanlist.find(Ptr->name);
932 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
934 /* kill the record */
935 if (iter != chanlist.end())
937 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
939 chanlist.erase(iter);
947 /* This function pokes and hacks at a parameter list like the following:
949 * PART #winbot,#darkgalaxy :m00!
951 * to turn it into a series of individual calls like this:
954 * PART #darkgalaxy :m00!
956 * The seperate calls are sent to a callback function provided by the caller
957 * (the caller will usually call itself recursively). The callback function
958 * must be a command handler. Calling this function on a line with no list causes
959 * no action to be taken. You must provide a starting and ending parameter number
960 * where the range of the list can be found, useful if you have a terminating
961 * parameter as above which is actually not part of the list, or parameters
962 * before the actual list as well. This code is used by many functions which
963 * can function as "one to list" (see the RFC) */
965 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
970 char blog[32][MAXBUF];
971 char blog2[32][MAXBUF];
972 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
976 for (int i = 0; i <32; i++)
979 for (int i = 0; i <32; i++)
983 for (int i = 0; i <10; i++)
992 if (pcnt > 1) /* we have a key to copy */
994 strlcpy(keystr,parameters[1],MAXBUF);
998 if (!parameters[start])
1002 if (!strchr(parameters[start],','))
1007 for (int i = start; i <= end; i++)
1011 strlcat(plist,parameters[i],MAXBUF);
1019 for (int i = 0; i < t; i++)
1021 if (plist[i] == ',')
1024 strlcpy(blog[j++],param,MAXBUF);
1028 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1033 strlcpy(blog[j++],param,MAXBUF);
1036 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1041 if ((joins) && (keystr))
1043 if (strchr(keystr,','))
1047 t2 = strlen(keystr);
1048 for (int i = 0; i < t2; i++)
1050 if (keystr[i] == ',')
1053 strlcpy(blog2[j++],param,MAXBUF);
1057 strlcpy(blog2[j++],param,MAXBUF);
1062 for (j = 0; j < total; j++)
1068 for (q = end; q < pcnt-1; q++)
1070 if (parameters[q+1])
1072 pars[q-end+1] = parameters[q+1];
1075 if ((joins) && (parameters[1]))
1086 /* repeatedly call the function with the hacked parameter list */
1087 if ((joins) && (pcnt > 1))
1091 // pars[1] already set up and containing key from blog2[j]
1096 pars[1] = parameters[1];
1102 fn(pars,pcnt-(end-start),u);
1111 void kill_link(userrec *user,const char* r)
1113 user_hash::iterator iter = clientlist.find(user->nick);
1115 char reason[MAXBUF];
1117 strncpy(reason,r,MAXBUF);
1119 if (strlen(reason)>MAXQUIT)
1121 reason[MAXQUIT-1] = '\0';
1124 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1125 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1126 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1128 if (user->registered == 7) {
1129 FOREACH_MOD OnUserQuit(user);
1130 WriteCommonExcept(user,"QUIT :%s",reason);
1132 // Q token must go to ALL servers!!!
1133 char buffer[MAXBUF];
1134 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1135 NetSendToAll(buffer);
1138 user->FlushWriteBuf();
1140 FOREACH_MOD OnUserDisconnect(user);
1144 FOREACH_MOD OnRawSocketClose(user->fd);
1147 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1148 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1151 log(DEBUG,"kqueue: Failed to remove user from queue!");
1155 struct epoll_event ev;
1156 ev.events = EPOLLIN | EPOLLET;
1157 ev.data.fd = user->fd;
1158 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1161 log(DEBUG,"epoll: List deletion failure!");
1164 user->CloseSocket();
1167 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1168 // if they were an oper with +s.
1169 if (user->registered == 7) {
1170 purge_empty_chans(user);
1171 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1172 if (!strcmp(user->server,ServerName))
1173 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1177 if (iter != clientlist.end())
1179 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1181 fd_ref_table[user->fd] = NULL;
1182 clientlist.erase(iter);
1187 void kill_link_silent(userrec *user,const char* r)
1189 user_hash::iterator iter = clientlist.find(user->nick);
1191 char reason[MAXBUF];
1193 strncpy(reason,r,MAXBUF);
1195 if (strlen(reason)>MAXQUIT)
1197 reason[MAXQUIT-1] = '\0';
1200 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1201 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1202 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1204 user->FlushWriteBuf();
1206 if (user->registered == 7) {
1207 FOREACH_MOD OnUserQuit(user);
1208 WriteCommonExcept(user,"QUIT :%s",reason);
1210 // Q token must go to ALL servers!!!
1211 char buffer[MAXBUF];
1212 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1213 NetSendToAll(buffer);
1216 FOREACH_MOD OnUserDisconnect(user);
1220 FOREACH_MOD OnRawSocketClose(user->fd);
1223 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1224 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1227 log(DEBUG,"kqueue: Failed to remove user from queue!");
1231 struct epoll_event ev;
1232 ev.events = EPOLLIN | EPOLLET;
1233 ev.data.fd = user->fd;
1234 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1237 log(DEBUG,"epoll: List deletion failure!");
1240 user->CloseSocket();
1243 if (user->registered == 7) {
1244 purge_empty_chans(user);
1247 if (iter != clientlist.end())
1249 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1251 fd_ref_table[user->fd] = NULL;
1252 clientlist.erase(iter);
1258 int main(int argc, char** argv)
1262 log(DEBUG,"*** InspIRCd starting up!");
1263 if (!FileExists(CONFIG_FILE))
1265 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1266 log(DEFAULT,"main: no config");
1267 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1271 for (int i = 1; i < argc; i++)
1273 if (!strcmp(argv[i],"-nofork")) {
1276 if (!strcmp(argv[i],"-wait")) {
1279 if (!strcmp(argv[i],"-nolimit")) {
1284 strlcpy(MyExecutable,argv[0],MAXBUF);
1286 // initialize the lowercase mapping table
1287 for (unsigned int cn = 0; cn < 256; cn++)
1289 // lowercase the uppercase chars
1290 for (unsigned int cn = 65; cn < 91; cn++)
1291 lowermap[cn] = tolower(cn);
1292 // now replace the specific chars for scandanavian comparison
1293 lowermap[(unsigned)'['] = '{';
1294 lowermap[(unsigned)']'] = '}';
1295 lowermap[(unsigned)'\\'] = '|';
1297 if (InspIRCd(argv,argc) == ERROR)
1299 log(DEFAULT,"main: daemon function bailed");
1300 printf("ERROR: could not initialise. Shutting down.\n");
1307 template<typename T> inline string ConvToStr(const T &in)
1310 if (!(tmp << in)) return string();
1314 /* re-allocates a nick in the user_hash after they change nicknames,
1315 * returns a pointer to the new user as it may have moved */
1317 userrec* ReHashNick(char* Old, char* New)
1319 //user_hash::iterator newnick;
1320 user_hash::iterator oldnick = clientlist.find(Old);
1322 log(DEBUG,"ReHashNick: %s %s",Old,New);
1324 if (!strcasecmp(Old,New))
1326 log(DEBUG,"old nick is new nick, skipping");
1327 return oldnick->second;
1330 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1332 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1334 userrec* olduser = oldnick->second;
1335 clientlist[New] = olduser;
1336 clientlist.erase(oldnick);
1338 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1340 return clientlist[New];
1343 /* adds or updates an entry in the whowas list */
1344 void AddWhoWas(userrec* u)
1346 whowas_hash::iterator iter = whowas.find(u->nick);
1347 WhoWasUser *a = new WhoWasUser();
1348 strlcpy(a->nick,u->nick,NICKMAX);
1349 strlcpy(a->ident,u->ident,IDENTMAX);
1350 strlcpy(a->dhost,u->dhost,160);
1351 strlcpy(a->host,u->host,160);
1352 strlcpy(a->fullname,u->fullname,MAXGECOS);
1353 strlcpy(a->server,u->server,256);
1354 a->signon = u->signon;
1356 /* MAX_WHOWAS: max number of /WHOWAS items
1357 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1358 * can be replaced by a newer one
1361 if (iter == whowas.end())
1363 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1365 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1367 // 3600 seconds in an hour ;)
1368 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1370 // delete the old one
1371 if (i->second) delete i->second;
1372 // replace with new one
1374 log(DEBUG,"added WHOWAS entry, purged an old record");
1378 // no space left and user doesnt exist. Don't leave ram in use!
1379 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1384 log(DEBUG,"added fresh WHOWAS entry");
1385 whowas[a->nick] = a;
1390 log(DEBUG,"updated WHOWAS entry");
1391 if (iter->second) delete iter->second;
1397 /* add a client connection to the sockets list */
1398 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1402 user_hash::iterator iter;
1404 tempnick = ConvToStr(socket) + "-unknown";
1405 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1407 iter = clientlist.find(tempnick);
1410 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1411 // using one as a registered connection. As theyre per fd, we can also safely assume
1412 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1413 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1414 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1415 // issue in earlier alphas/betas
1416 if (iter != clientlist.end())
1418 userrec* goner = iter->second;
1420 clientlist.erase(iter);
1424 * It is OK to access the value here this way since we know
1425 * it exists, we just created it above.
1427 * At NO other time should you access a value in a map or a
1428 * hash_map this way.
1430 clientlist[tempnick] = new userrec();
1432 NonBlocking(socket);
1433 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1435 clientlist[tempnick]->fd = socket;
1436 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1437 strlcpy(clientlist[tempnick]->host, host,160);
1438 strlcpy(clientlist[tempnick]->dhost, host,160);
1439 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1440 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1441 clientlist[tempnick]->registered = 0;
1442 clientlist[tempnick]->signon = TIME+dns_timeout;
1443 clientlist[tempnick]->lastping = 1;
1444 clientlist[tempnick]->port = port;
1445 strlcpy(clientlist[tempnick]->ip,ip,16);
1447 // set the registration timeout for this user
1448 unsigned long class_regtimeout = 90;
1449 int class_flood = 0;
1450 long class_threshold = 5;
1451 long class_sqmax = 262144; // 256kb
1452 long class_rqmax = 4096; // 4k
1454 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1456 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1458 class_regtimeout = (unsigned long)i->registration_timeout;
1459 class_flood = i->flood;
1460 clientlist[tempnick]->pingmax = i->pingtime;
1461 class_threshold = i->threshold;
1462 class_sqmax = i->sendqmax;
1463 class_rqmax = i->recvqmax;
1468 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1469 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1470 clientlist[tempnick]->flood = class_flood;
1471 clientlist[tempnick]->threshold = class_threshold;
1472 clientlist[tempnick]->sendqmax = class_sqmax;
1473 clientlist[tempnick]->recvqmax = class_rqmax;
1475 for (int i = 0; i < MAXCHANS; i++)
1477 clientlist[tempnick]->chans[i].channel = NULL;
1478 clientlist[tempnick]->chans[i].uc_modes = 0;
1481 if (clientlist.size() > SoftLimit)
1483 kill_link(clientlist[tempnick],"No more connections allowed");
1487 if (clientlist.size() >= MAXCLIENTS)
1489 kill_link(clientlist[tempnick],"No more connections allowed");
1493 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1494 // its a pretty big but for the moment valid assumption:
1495 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1496 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1497 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1498 // which for the time being is a physical impossibility (even the largest networks dont have more
1499 // than about 10,000 users on ONE server!)
1500 if ((unsigned)socket > 65534)
1502 kill_link(clientlist[tempnick],"Server is full");
1507 char* e = matches_exception(ip);
1510 char* r = matches_zline(ip);
1513 char reason[MAXBUF];
1514 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1515 kill_link(clientlist[tempnick],reason);
1519 fd_ref_table[socket] = clientlist[tempnick];
1522 struct epoll_event ev;
1523 log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1524 ev.events = EPOLLIN | EPOLLET;
1525 ev.data.fd = socket;
1526 int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1529 log(DEBUG,"epoll: List insertion failure!");
1534 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1535 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1536 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1539 log(DEBUG,"kqueue: List insertion failure!");
1545 /* shows the message of the day, and any other on-logon stuff */
1546 void FullConnectUser(userrec* user)
1549 user->idle_lastmsg = TIME;
1550 log(DEBUG,"ConnectUser: %s",user->nick);
1552 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1554 kill_link(user,"Invalid password");
1559 kill_link(user,"Unauthorised connection");
1563 char match_against[MAXBUF];
1564 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1565 char* e = matches_exception(match_against);
1568 char* r = matches_gline(match_against);
1571 char reason[MAXBUF];
1572 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1573 kill_link_silent(user,reason);
1576 r = matches_kline(user->host);
1579 char reason[MAXBUF];
1580 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1581 kill_link_silent(user,reason);
1586 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1587 user->registered = 7;
1589 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1590 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1591 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1592 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1593 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1594 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1595 std::stringstream v;
1596 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1597 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1598 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1600 std::string data005 = v.str();
1601 FOREACH_MOD On005Numeric(data005);
1602 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1603 // so i'd better split it :)
1604 std::stringstream out(data005);
1605 std::string token = "";
1606 std::string line5 = "";
1607 int token_counter = 0;
1611 line5 = line5 + token + " ";
1613 if ((token_counter >= 13) || (out.eof() == true))
1615 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1622 char buffer[MAXBUF];
1623 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);
1624 NetSendToAll(buffer);
1626 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1627 FOREACH_MOD OnUserConnect(user);
1628 FOREACH_MOD OnGlobalConnect(user);
1629 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1633 /* shows the message of the day, and any other on-logon stuff */
1634 void ConnectUser(userrec *user)
1636 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1637 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1639 FullConnectUser(user);
1643 std::string GetVersionString()
1645 char Revision[] = "$Revision$";
1646 char versiondata[MAXBUF];
1647 char *s1 = Revision;
1649 char *v2 = strtok_r(s1," ",&savept);
1651 v2 = strtok_r(s1," ",&savept);
1654 char socketengine[] = "kqueue";
1657 char socketengine[] = "select";
1660 char socketengine[] = "epoll";
1662 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1666 void handle_version(char **parameters, int pcnt, userrec *user)
1670 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1674 if (!strcmp(parameters[0],"*"))
1676 for (int j = 0; j < 32; j++)
1680 for (unsigned int x = 0; x < me[j]->connectors.size(); x++)
1682 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());
1688 if (match(ServerName,parameters[0]))
1690 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1693 bool displayed = false, found = false;
1694 for (int j = 0; j < 32; j++)
1698 for (unsigned int x = 0; x < me[j]->connectors.size(); x++)
1700 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1703 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1706 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1712 if ((!displayed) && (found))
1714 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1719 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1726 // calls a handler function for a command
1728 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1730 for (unsigned int i = 0; i < cmdlist.size(); i++)
1732 if (!strcasecmp(cmdlist[i].command,commandname))
1734 if (cmdlist[i].handler_function)
1736 if (pcnt>=cmdlist[i].min_params)
1738 if (strchr(user->modes,cmdlist[i].flags_needed))
1740 cmdlist[i].handler_function(parameters,pcnt,user);
1748 void DoSplitEveryone()
1750 bool go_again = true;
1754 for (int i = 0; i < 32; i++)
1758 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1760 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1763 j->CloseConnection();
1764 me[i]->connectors.erase(j);
1772 log(DEBUG,"Removed server. Will remove clients...");
1773 // iterate through the userlist and remove all users on this server.
1774 // because we're dealing with a mesh, we dont have to deal with anything
1775 // "down-route" from this server (nice huh)
1777 char reason[MAXBUF];
1781 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1783 if (strcasecmp(u->second->server,ServerName))
1785 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1786 kill_link(u->second,reason);
1792 has_been_netsplit = true;
1793 log(DEBUG,"Clients removed.");
1798 void force_nickchange(userrec* user,const char* newnick)
1805 FOREACH_RESULT(OnUserPreNick(user,newnick));
1808 kill_link(user,"Nickname collision");
1811 if (matches_qline(newnick))
1814 kill_link(user,"Nickname collision");
1822 strncpy(nick,newnick,MAXBUF);
1824 if (user->registered == 7)
1828 handle_nick(pars,1,user);
1834 int process_parameters(char **command_p,char *parameters)
1837 int q = strlen(parameters);
1840 /* no parameters, command_p invalid! */
1843 if (parameters[0] == ':')
1845 command_p[0] = parameters+1;
1850 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1852 /* only one parameter */
1853 command_p[0] = parameters;
1854 if (parameters[0] == ':')
1856 if (strchr(parameters,' ') != NULL)
1864 command_p[j++] = parameters;
1865 for (int i = 0; i <= q; i++)
1867 if (parameters[i] == ' ')
1869 command_p[j++] = parameters+i+1;
1870 parameters[i] = '\0';
1871 if (command_p[j-1][0] == ':')
1873 *command_p[j-1]++; /* remove dodgy ":" */
1875 /* parameter like this marks end of the sequence */
1879 return j; /* returns total number of items in the list */
1882 void process_command(userrec *user, char* cmd)
1886 char *command_p[127];
1887 char p[MAXBUF], temp[MAXBUF];
1888 int j, items, cmd_found;
1890 for (int i = 0; i < 127; i++)
1891 command_p[i] = NULL;
1906 int total_params = 0;
1909 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1911 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1914 // found a 'trailing', we dont count them after this.
1922 // another phidjit bug...
1923 if (total_params > 126)
1925 *(strchr(cmd,' ')) = '\0';
1926 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1930 strlcpy(temp,cmd,MAXBUF);
1932 std::string tmp = cmd;
1933 for (int i = 0; i <= MODCOUNT; i++)
1935 std::string oldtmp = tmp;
1936 modules[i]->OnServerRaw(tmp,true,user);
1939 log(DEBUG,"A Module changed the input string!");
1940 log(DEBUG,"New string: %s",tmp.c_str());
1941 log(DEBUG,"Old string: %s",oldtmp.c_str());
1945 strlcpy(cmd,tmp.c_str(),MAXBUF);
1946 strlcpy(temp,cmd,MAXBUF);
1948 if (!strchr(cmd,' '))
1950 /* no parameters, lets skip the formalities and not chop up
1952 log(DEBUG,"About to preprocess command with no params");
1954 command_p[0] = NULL;
1956 for (unsigned int i = 0; i <= strlen(cmd); i++)
1958 cmd[i] = toupper(cmd[i]);
1966 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1967 for (unsigned int i = 0; i < strlen(temp); i++)
1969 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1975 /* split the full string into a command plus parameters */
1979 if (strchr(cmd,' '))
1981 for (unsigned int i = 0; i <= strlen(cmd); i++)
1983 /* capitalise the command ONLY, leave params intact */
1984 cmd[i] = toupper(cmd[i]);
1985 /* are we nearly there yet?! :P */
1989 parameters = cmd+i+1;
1997 for (unsigned int i = 0; i <= strlen(cmd); i++)
1999 cmd[i] = toupper(cmd[i]);
2006 if (strlen(command)>MAXCOMMAND)
2008 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
2012 for (unsigned int x = 0; x < strlen(command); x++)
2014 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2016 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2018 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2021 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2028 for (unsigned int i = 0; i != cmdlist.size(); i++)
2030 if (cmdlist[i].command[0])
2032 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2038 items = process_parameters(command_p,parameters);
2043 command_p[0] = NULL;
2049 command_p[0] = NULL;
2054 /* activity resets the ping pending timer */
2055 user->nping = TIME + user->pingmax;
2056 if ((items) < cmdlist[i].min_params)
2058 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2059 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2062 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2064 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2065 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2069 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2071 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2072 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2076 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2078 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2080 if ((!isnick(user->nick)) || (user->registered != 7))
2082 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2083 WriteServ(user->fd,"451 %s :You have not registered",command);
2087 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2089 std::stringstream dcmds(DisabledCommands);
2090 while (!dcmds.eof())
2092 std::string thiscmd;
2094 if (!strcasecmp(thiscmd.c_str(),command))
2096 // command is disabled!
2097 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2102 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2104 if (cmdlist[i].handler_function)
2107 /* ikky /stats counters */
2110 cmdlist[i].use_count++;
2111 cmdlist[i].total_bytes+=strlen(temp);
2115 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2116 if (MOD_RESULT == 1) {
2120 /* WARNING: nothing may come after the
2121 * command handler call, as the handler
2122 * may free the user structure! */
2124 cmdlist[i].handler_function(command_p,items,user);
2130 WriteServ(user->fd,"451 %s :You have not registered",command);
2138 if ((!cmd_found) && (user))
2141 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2145 bool removecommands(const char* source)
2147 bool go_again = true;
2151 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2153 if (!strcmp(i->source,source))
2155 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2166 void process_buffer(const char* cmdbuf,userrec *user)
2170 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2176 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2183 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2185 strlcpy(cmd,cmdbuf,MAXBUF);
2190 int sl = strlen(cmd)-1;
2191 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2196 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2201 while (cmd[sl] == ' ') // strip trailing spaces
2211 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2213 if ((user) && (cmd))
2215 process_command(user,cmd);
2219 void DoSync(serverrec* serv, char* tcp_host)
2222 log(DEBUG,"Sending sync");
2223 // send start of sync marker: Y <timestamp>
2224 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2225 // except the ones its receiving it from.
2226 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2227 serv->SendPacket(data,tcp_host);
2228 // send users and channels
2230 NetSendMyRoutingTable();
2232 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2233 for (int j = 0; j < 32; j++)
2237 for (unsigned int k = 0; k < me[j]->connectors.size(); k++)
2239 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2241 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2242 serv->SendPacket(data,tcp_host);
2248 // send our version for the remote side to cache
2249 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2250 serv->SendPacket(data,tcp_host);
2252 // sync the users and channels, give the modules a look-in.
2253 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2255 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);
2256 serv->SendPacket(data,tcp_host);
2257 if (strchr(u->second->modes,'o'))
2259 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2260 serv->SendPacket(data,tcp_host);
2262 for (int i = 0; i <= MODCOUNT; i++)
2264 string_list l = modules[i]->OnUserSync(u->second);
2265 for (unsigned int j = 0; j < l.size(); j++)
2267 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2268 serv->SendPacket(data,tcp_host);
2271 char* chl = chlist(u->second,u->second);
2274 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2275 serv->SendPacket(data,tcp_host);
2278 // send channel modes, topics etc...
2279 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2281 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2282 serv->SendPacket(data,tcp_host);
2283 for (int i = 0; i <= MODCOUNT; i++)
2285 string_list l = modules[i]->OnChannelSync(c->second);
2286 for (unsigned int j = 0; j < l.size(); j++)
2288 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2289 serv->SendPacket(data,tcp_host);
2292 if (c->second->topic[0])
2294 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);
2295 serv->SendPacket(data,tcp_host);
2297 // send current banlist
2299 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2301 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2302 serv->SendPacket(data,tcp_host);
2305 // sync global zlines, glines, etc
2306 sync_xlines(serv,tcp_host);
2308 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2309 serv->SendPacket(data,tcp_host);
2310 log(DEBUG,"Sent sync");
2311 // ircd sends its serverlist after the end of sync here
2315 void NetSendMyRoutingTable()
2317 // send out a line saying what is reachable to us.
2318 // E.g. if A is linked to B C and D, send out:
2320 // if its only linked to B and D send out:
2322 // if it has no links, dont even send out the line at all.
2323 char buffer[MAXBUF];
2324 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2325 bool sendit = false;
2326 for (int i = 0; i < 32; i++)
2330 for (unsigned int j = 0; j < me[i]->connectors.size(); j++)
2332 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2334 strlcat(buffer," ",MAXBUF);
2335 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2342 NetSendToAll(buffer);
2346 void DoSplit(const char* params)
2348 bool go_again = true;
2352 for (int i = 0; i < 32; i++)
2356 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2358 if (!strcasecmp(j->GetServerName().c_str(),params))
2361 j->CloseConnection();
2362 me[i]->connectors.erase(j);
2370 log(DEBUG,"Removed server. Will remove clients...");
2371 // iterate through the userlist and remove all users on this server.
2372 // because we're dealing with a mesh, we dont have to deal with anything
2373 // "down-route" from this server (nice huh)
2375 char reason[MAXBUF];
2376 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2380 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2382 if (!strcasecmp(u->second->server,params))
2384 kill_link(u->second,reason);
2390 has_been_netsplit = true;
2391 log(DEBUG,"Removed clients (DoSplit)");
2394 // removes a server. Will NOT remove its users!
2396 void RemoveServer(const char* name)
2398 bool go_again = true;
2402 for (int i = 0; i < 32; i++)
2406 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2408 if (!strcasecmp(j->GetServerName().c_str(),name))
2411 j->CloseConnection();
2412 me[i]->connectors.erase(j);
2423 char MODERR[MAXBUF];
2430 void erase_factory(int j)
2433 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2438 factory.push_back(NULL);
2445 void erase_module(int j)
2448 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2454 modules.push_back(NULL);
2460 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2464 module_names.erase(v);
2472 bool UnloadModule(const char* filename)
2474 std::string filename_str = filename;
2475 for (unsigned int j = 0; j != module_names.size(); j++)
2477 if (module_names[j] == filename_str)
2479 if (modules[j]->GetVersion().Flags & VF_STATIC)
2481 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2482 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2485 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2487 log(DEBUG,"Deleting module...");
2489 log(DEBUG,"Erasing module entry...");
2491 log(DEBUG,"Removing dependent commands...");
2492 removecommands(filename);
2493 log(DEFAULT,"Module %s unloaded",filename);
2498 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2499 snprintf(MODERR,MAXBUF,"Module not loaded");
2503 bool LoadModule(const char* filename)
2505 char modfile[MAXBUF];
2507 snprintf(modfile,MAXBUF,"%s",filename);
2509 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2511 std::string filename_str = filename;
2513 if (!DirValid(modfile))
2515 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2516 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2520 log(DEBUG,"Loading module: %s",modfile);
2522 if (FileExists(modfile))
2525 for (unsigned int j = 0; j < module_names.size(); j++)
2527 if (module_names[j] == filename_str)
2529 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2530 snprintf(MODERR,MAXBUF,"Module already loaded");
2534 ircd_module* a = new ircd_module(modfile);
2535 factory[MODCOUNT+1] = a;
2536 if (factory[MODCOUNT+1]->LastError())
2538 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2539 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2543 if (factory[MODCOUNT+1]->factory)
2545 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2546 modules[MODCOUNT+1] = m;
2547 /* save the module and the module's classfactory, if
2548 * this isnt done, random crashes can occur :/ */
2549 module_names.push_back(filename);
2553 log(DEFAULT,"Unable to load %s",modfile);
2554 snprintf(MODERR,MAXBUF,"Factory function failed!");
2561 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2562 snprintf(MODERR,MAXBUF,"Module file could not be found");
2567 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2572 bool GotServer(std::string name)
2574 for (int j = 0; j < 32; j++)
2578 for (unsigned int k = 0; k < me[j]->connectors.size(); k++)
2580 if (name == me[j]->connectors[k].GetServerName())
2591 int InspIRCd(char** argv, int argc)
2593 struct sockaddr_in client,server;
2594 char addrs[MAXBUF][255];
2595 int incomingSockfd, result = TRUE;
2599 int selectResult = 0, selectResult2 = 0;
2602 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2605 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2606 log_file = fopen(logpath.c_str(),"a+");
2609 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2614 printf("Logging to ircd.log...\n");
2616 printf("Logging to %s...\n",logpath.c_str());
2619 log(DEFAULT,"$Id$");
2622 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2624 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2626 SetupCommandTable();
2627 log(DEBUG,"InspIRCd: startup: default command table set up");
2629 ReadConfig(true,NULL);
2632 printf("WARNING: %s\n\n",DieValue);
2633 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2636 log(DEBUG,"InspIRCd: startup: read config");
2638 AddServerName(ServerName);
2640 int clientportcount = 0, serverportcount = 0;
2642 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2644 ConfValue("bind","port",count,configToken,&config_f);
2645 ConfValue("bind","address",count,Addr,&config_f);
2646 ConfValue("bind","type",count,Type,&config_f);
2647 if (!strcmp(Type,"servers"))
2649 char Default[MAXBUF];
2650 strcpy(Default,"no");
2651 ConfValue("bind","default",count,Default,&config_f);
2652 if (strchr(Default,'y'))
2654 defaultRoute = serverportcount;
2655 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2657 me[serverportcount] = new serverrec(ServerName,100L,false);
2658 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2660 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2661 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2670 ports[clientportcount] = atoi(configToken);
2671 strlcpy(addrs[clientportcount],Addr,256);
2674 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2676 portCount = clientportcount;
2677 SERVERportCount = serverportcount;
2679 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2680 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2684 /* BugFix By Craig! :p */
2686 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2688 ConfValue("module","name",count,configToken,&config_f);
2689 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2690 if (!LoadModule(configToken))
2692 log(DEFAULT,"Exiting due to a module loader error.");
2693 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2697 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2699 startup_time = time(NULL);
2702 ConfValue("pid","file",0,PID,&config_f);
2703 // write once here, to try it out and make sure its ok
2706 /* setup select call */
2708 FD_ZERO(&selectFds);
2710 log(DEBUG,"InspIRCd: startup: zero selects");
2711 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2713 for (count = 0; count < portCount; count++)
2715 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2717 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2720 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2722 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2724 else /* well we at least bound to one socket so we'll continue */
2730 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2732 /* if we didn't bind to anything then abort */
2733 if (boundPortCount == 0)
2735 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2736 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2741 printf("\nInspIRCd is now running!\n");
2745 log(VERBOSE,"Not forking as -nofork was specified");
2749 if (DaemonSeed() == ERROR)
2751 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2752 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2757 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2762 if ((kq == -1) || (lkq == -1) || (skq == -1))
2764 log(DEFAULT,"main: kqueue() failed!");
2765 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2771 ep = epoll_create(MAXCLIENTS);
2772 lep = epoll_create(32);
2773 sep = epoll_create(128);
2774 if ((ep == -1) || (lep == -1) || (sep == -1))
2776 log(DEFAULT,"main: epoll_create() failed!");
2777 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2783 log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2784 for (count = 0; count < boundPortCount; count++)
2786 struct epoll_event ev;
2787 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2788 ev.events = EPOLLIN | EPOLLET;
2789 ev.data.fd = openSockfd[count];
2790 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2793 log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2794 printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2799 for (int t = 0; t != SERVERportCount; t++)
2801 struct epoll_event ev;
2802 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2803 ev.events = EPOLLIN | EPOLLET;
2804 ev.data.fd = me[t]->fd;
2805 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2808 log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2809 printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2815 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2816 for (count = 0; count < boundPortCount; count++)
2819 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2820 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2821 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2824 log(DEFAULT,"main: add listen ports to kqueue failed!");
2825 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2829 for (int t = 0; t != SERVERportCount; t++)
2834 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2835 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2836 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2839 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2840 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2848 log(DEFAULT,"Using standard select socket engine.");
2854 length = sizeof (client);
2855 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2859 struct kevent ke_list[33];
2863 struct epoll_event event[33];
2870 tvs.tv_usec = 10000L;
2873 tv.tv_usec = 10000L;
2876 tval.tv_usec = 10000L;
2878 int total_in_this_set = 0;
2879 int i = 0, v = 0, j = 0, cycle_iter = 0;
2880 bool expire_run = false;
2882 cycle_iter = i = j = 0; // stop the compiler whining - these may be marked unused in certain socket engine types
2884 /* main loop, this never returns */
2887 #ifdef _POSIX_PRIORITY_SCHEDULING
2893 // we only read time() once per iteration rather than tons of times!
2899 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2900 // them in a list, then reap the list every second or so.
2901 if (((TIME % 5) == 0) && (!expire_run))
2903 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2905 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2906 ConfValue("link","name",i,Link_ServerName,&config_f);
2907 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2908 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2910 autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2911 if (a != autoconns.end())
2913 if (TIME > a->second)
2915 ConnectServer(Link_ServerName,NULL);
2916 a->second = TIME + atoi(Link_AConn);
2923 FOREACH_MOD OnBackgroundTimer(TIME);
2927 if ((TIME % 5) == 1)
2930 // fix by brain - this must be below any manipulation of the hashmap by modules
2931 user_hash::iterator count2 = clientlist.begin();
2934 i = epoll_wait(sep, event, 1, EP_DELAY);
2937 log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2938 for (int x = 0; x != SERVERportCount; x++)
2940 if ((me[x]) && ((unsigned)event[0].data.fd == (unsigned)me[x]->fd))
2945 ts.tv_nsec = 30000L;
2946 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2949 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2950 for (int x = 0; x != SERVERportCount; x++)
2952 if ((me[x]) && ((unsigned)ke.ident == (unsigned)me[x]->fd))
2957 FD_ZERO(&serverfds);
2958 for (int x = 0; x != SERVERportCount; x++)
2961 FD_SET(me[x]->fd, &serverfds);
2963 tvs.tv_usec = 30000L;
2965 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2968 for (int x = 0; x != SERVERportCount; x++)
2970 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2973 char remotehost[MAXBUF],resolved[MAXBUF];
2974 length = sizeof (client);
2975 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2976 if (incomingSockfd != -1)
2978 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2979 if(CleanAndResolve(resolved, remotehost) != TRUE)
2981 strlcpy(resolved,remotehost,MAXBUF);
2983 // add to this connections ircd_connector vector
2984 // *FIX* - we need the LOCAL port not the remote port in &client!
2985 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2991 std::deque<std::string> msgs;
2992 std::deque<std::string> sums;
2993 for (int x = 0; x < SERVERportCount; x++)
2996 me[x]->FlushWriteBuffers();
3000 has_been_netsplit = false;
3001 while (me[x]->RecvPacket(msgs, tcp_host, sums)) // returns 0 or more lines (can be multiple lines!)
3003 if (has_been_netsplit)
3005 log("Netsplit detected in recvpacket, aborting");
3008 for (unsigned int ctr = 0; ctr < msgs.size(); ctr++)
3010 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
3011 strlcpy(tcp_sum,sums[ctr].c_str(),MAXBUF);
3012 log(DEBUG,"Processing: %s",tcp_msg);
3015 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
3018 // during a netburst, send all data to all other linked servers
3019 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3021 if (is_uline(tcp_host))
3023 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
3025 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
3029 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
3031 std::string msg = tcp_msg;
3032 FOREACH_MOD OnPacketReceive(msg,tcp_host);
3033 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
3035 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
3036 if (!me[x]->FindHost(tcp_host))
3038 log(DEBUG,"Connector gone, bailing!");
3046 while (count2 != clientlist.end())
3052 total_in_this_set = 0;
3054 user_hash::iterator xcount = count2;
3055 user_hash::iterator endingiter = count2;
3057 if (count2 == clientlist.end()) break;
3059 userrec* curr = NULL;
3062 curr = count2->second;
3064 if ((long)curr == -1)
3067 if ((curr) && (curr->fd != 0))
3069 #ifdef _POSIX_PRIORITY_SCHEDULING
3072 // assemble up to 64 sockets into an fd_set
3073 // to implement a pooling mechanism.
3075 // This should be up to 64x faster than the
3076 // old implementation.
3078 while (total_in_this_set < 1024)
3080 if (count2 != clientlist.end())
3082 curr = count2->second;
3083 if ((long)curr == -1)
3085 int currfd = curr->fd;
3086 // we don't check the state of remote users.
3087 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3089 curr->FlushWriteBuf();
3090 if (curr->GetWriteError() != "")
3092 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3093 kill_link(curr,curr->GetWriteError().c_str());
3097 FD_SET (curr->fd, &sfd);
3099 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3100 // their connection class.
3101 if ((TIME > (unsigned)curr->timeout) && (curr->registered != 7))
3103 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3104 kill_link(curr,"Registration timeout");
3107 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3109 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3110 curr->dns_done = true;
3112 FullConnectUser(curr);
3113 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3116 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3118 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3119 FullConnectUser(curr);
3120 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3123 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3125 if ((!curr->lastping) && (curr->registered == 7))
3127 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3128 kill_link(curr,"Ping timeout");
3131 Write(curr->fd,"PING :%s",ServerName);
3132 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3134 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3138 total_in_this_set++;
3142 endingiter = count2;
3143 count2 = xcount; // roll back to where we were
3145 // 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.
3146 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3148 if (cycle_iter > 20) while (count2 != clientlist.end())
3151 if (count2 != clientlist.end())
3153 curr = count2->second;
3154 if ((long)curr == -1)
3156 int currfd = curr->fd;
3157 // we don't check the state of remote users.
3158 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3161 curr->FlushWriteBuf();
3162 if (curr->GetWriteError() != "")
3164 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3165 kill_link(curr,curr->GetWriteError().c_str());
3169 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3170 // their connection class.
3171 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
3173 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3174 kill_link(curr,"Registration timeout");
3178 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3180 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3181 curr->dns_done = true;
3183 FullConnectUser(curr);
3184 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3187 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3189 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3190 FullConnectUser(curr);
3191 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3194 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3196 if ((!curr->lastping) && (curr->registered == 7))
3198 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3199 kill_link(curr,"Ping timeout");
3202 Write(curr->fd,"PING :%s",ServerName);
3203 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3205 curr->nping = TIME+curr->pingmax; // was hard coded to 120
3212 // increment the counter right to the end of the list, as kqueue processes everything in one go
3217 int i = epoll_wait(ep, event, 1, 5);
3220 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3221 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3222 userrec* cu = fd_ref_table[event[0].data.fd];
3227 // for now, we only read 1 event. We could read soooo many more :)
3228 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3231 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3232 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3233 userrec* cu = fd_ref_table[ke.ident];
3237 tval.tv_usec = 1000L;
3238 selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3239 // now loop through all of the items in this pool if any are waiting
3240 if ((selectResult2 > 0) && (xcount != clientlist.end()))
3241 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3243 // SELECT: we have to iterate...
3244 if (count2a == clientlist.end())
3246 userrec* cu = count2a->second;
3249 #ifdef _POSIX_PRIORITY_SCHEDULING
3254 // EPOLL: We already know we have a valid FD. No checks needed.
3255 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3258 // KQUEUE: We already know we have a valid FD. No checks needed.
3259 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3262 // SELECT: We don't know if our FD is valid.
3263 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3266 log(DEBUG,"Data waiting on socket %d",cu->fd);
3269 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3272 result = cu->ReadData(data, 65535);
3276 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
3279 log(DEBUG,"Read result: %d",result);
3282 statsRecv += result;
3283 // perform a check on the raw buffer as an array (not a string!) to remove
3284 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3285 // hopefully this should stop even more people whining about "Unknown command: *"
3286 for (int checker = 0; checker < result; checker++)
3288 if ((data[checker] == 0) || (data[checker] == 7))
3289 data[checker] = ' ';
3292 data[result] = '\0';
3293 userrec* current = cu;
3294 int currfd = current->fd;
3296 // add the data to the users buffer
3298 if (!current->AddBuffer(data))
3300 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3301 if (current->registered == 7)
3303 kill_link(current,"RecvQ exceeded");
3307 WriteOpers("*** Excess flood from %s",current->ip);
3308 log(DEFAULT,"Excess flood from: %s",current->ip);
3309 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3314 if (current->recvq.length() > (unsigned)NetBufferSize)
3316 if (current->registered == 7)
3318 kill_link(current,"RecvQ exceeded");
3322 WriteOpers("*** Excess flood from %s",current->ip);
3323 log(DEFAULT,"Excess flood from: %s",current->ip);
3324 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3329 // while there are complete lines to process...
3330 while (current->BufferIsReady())
3333 if (TIME > current->reset_due)
3335 current->reset_due = TIME + current->threshold;
3336 current->lines_in = 0;
3338 current->lines_in++;
3339 if (current->lines_in > current->flood)
3341 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3342 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3343 kill_link(current,"Excess flood");
3346 if ((floodlines > current->flood) && (current->flood != 0))
3348 if (current->registered == 7)
3350 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3351 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3352 kill_link(current,"Excess flood");
3356 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3361 char sanitized[MAXBUF];
3362 // use GetBuffer to copy single lines into the sanitized string
3363 std::string single_line = current->GetBuffer();
3364 current->bytes_in += single_line.length();
3366 if (single_line.length()>512)
3368 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3369 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3370 kill_link(current,"Excess flood");
3373 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3376 userrec* old_comp = fd_ref_table[currfd];
3377 // we're gonna re-scan to check if the nick is gone, after every
3378 // command - if it has, we're gonna bail
3379 process_buffer(sanitized,current);
3380 // look for the user's record in case it's changed... if theyve quit,
3381 // we cant do anything more with their buffer, so bail.
3382 // there used to be an ugly, slow loop here. Now we have a reference
3383 // table, life is much easier (and FASTER)
3384 userrec* new_comp = fd_ref_table[currfd];
3385 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3393 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3395 log(DEBUG,"killing: %s",cu->nick);
3396 kill_link(cu,strerror(errno));
3400 // result EAGAIN means nothing read
3401 if (result == EAGAIN)
3411 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3412 kill_link(cu,"Client exited");
3413 // must bail here? kill_link removes the hash, corrupting the iterator
3414 log(DEBUG,"Bailing from client exit");
3420 else if (result > 0)
3425 for (int q = 0; q < total_in_this_set; q++)
3431 #ifdef _POSIX_PRIORITY_SCHEDULING
3436 // set up select call
3437 for (count = 0; count < boundPortCount; count++)
3439 FD_SET (openSockfd[count], &selectFds);
3442 tv.tv_usec = 30000L;
3443 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3445 /* select is reporting a waiting socket. Poll them all to find out which */
3446 if (selectResult > 0)
3448 for (count = 0; count < boundPortCount; count++)
3450 if (FD_ISSET (openSockfd[count], &selectFds))
3455 ts.tv_nsec = 30000L;
3456 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3457 if (i > 0) for (j = 0; j < i; j++)
3459 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3460 // this isnt as efficient as it could be, we could create a reference table
3461 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3462 // number of listening ports on the average ircd is a small number (less than 20)
3463 // compared to the number of clients (possibly over 2000)
3464 for (count = 0; count < boundPortCount; count++)
3466 if ((unsigned)ke_list[j].ident == (unsigned)openSockfd[count])
3470 i = epoll_wait(lep, event, 32, EP_DELAY);
3471 if (i > 0) for (j = 0; j < i; j++)
3473 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3474 for (count = 0; count < boundPortCount; count++)
3476 if ((unsigned)event[j].data.fd == (unsigned)openSockfd[count])
3479 char target[MAXBUF], resolved[MAXBUF];
3480 length = sizeof (client);
3481 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3483 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3484 strlcpy (resolved, target, MAXBUF);
3486 if (incomingSockfd < 0)
3488 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3489 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3494 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3496 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3497 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3504 #ifdef _POSIX_PRIORITY_SCHEDULING
3510 close (incomingSockfd);