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>
31 #include <sys/types.h>
32 #include <sys/event.h>
39 #include <ext/hash_map>
51 #include "connection.h"
63 #include "inspstring.h"
65 #include "helperfuncs.h"
68 int LogLevel = DEFAULT;
69 char ServerName[MAXBUF];
71 char ServerDesc[MAXBUF];
72 char AdminName[MAXBUF];
73 char AdminEmail[MAXBUF];
74 char AdminNick[MAXBUF];
76 char restartpass[MAXBUF];
80 char PrefixQuit[MAXBUF];
81 char DieValue[MAXBUF];
82 char DNSServer[MAXBUF];
84 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
85 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
87 time_t startup_time = time(NULL);
88 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
89 extern int MaxWhoResults;
93 char DisabledCommands[MAXBUF];
95 bool AllowHalfop = true;
96 bool AllowProtect = true;
97 bool AllowFounder = true;
99 extern std::vector<Module*> modules;
100 std::vector<std::string> module_names;
101 extern std::vector<ircd_module*> factory;
104 int openSockfd[MAXSOCKS];
106 bool unlimitcore = false;
108 time_t TIME = time(NULL), OLDTIME = time(NULL);
114 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
115 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
116 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
117 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, StrHashComp> whowas_hash;
118 typedef std::deque<command_t> command_table;
120 // This table references users by file descriptor.
121 // its an array to make it VERY fast, as all lookups are referenced
122 // by an integer, meaning there is no need for a scan/search operation.
123 userrec* fd_ref_table[65536];
125 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
131 user_hash clientlist;
134 command_table cmdlist;
141 struct linger linger = { 0 };
142 char MyExecutable[1024];
143 int boundPortCount = 0;
144 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
145 int defaultRoute = 0;
146 char ModPath[MAXBUF];
150 int has_channel(userrec *u, chanrec *c);
151 int usercount(chanrec *c);
152 int usercount_i(chanrec *c);
153 char* Passwd(userrec *user);
154 bool IsDenied(userrec *user);
155 void AddWhoWas(userrec* u);
157 std::vector<long> auth_cookies;
158 std::stringstream config_f(stringstream::in | stringstream::out);
160 std::vector<userrec*> all_opers;
164 void AddOper(userrec* user)
166 log(DEBUG,"Oper added to optimization list");
167 all_opers.push_back(user);
170 void DeleteOper(userrec* user)
172 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
176 log(DEBUG,"Oper removed from optimization list");
185 char Revision[] = "$Revision$";
188 char *v2 = strtok_r(s1," ",&savept);
190 v2 = strtok_r(s1," ",&savept);
192 return (long)(atof(v2)*10000);
196 std::string getservername()
201 std::string getserverdesc()
206 std::string getnetworkname()
211 std::string getadminname()
216 std::string getadminemail()
221 std::string getadminnick()
226 void ReadConfig(bool bail, userrec* user)
228 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
229 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
231 std::stringstream errstr;
233 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
238 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
246 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
247 while (!errstr.eof())
249 errstr.getline(dataline,1024);
250 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
255 WriteOpers("There were errors in the configuration file:",user->nick);
256 while (!errstr.eof())
258 errstr.getline(dataline,1024);
259 WriteOpers(dataline);
266 ConfValue("server","name",0,ServerName,&config_f);
267 ConfValue("server","description",0,ServerDesc,&config_f);
268 ConfValue("server","network",0,Network,&config_f);
269 ConfValue("admin","name",0,AdminName,&config_f);
270 ConfValue("admin","email",0,AdminEmail,&config_f);
271 ConfValue("admin","nick",0,AdminNick,&config_f);
272 ConfValue("files","motd",0,motd,&config_f);
273 ConfValue("files","rules",0,rules,&config_f);
274 ConfValue("power","diepass",0,diepass,&config_f);
275 ConfValue("power","pause",0,pauseval,&config_f);
276 ConfValue("power","restartpass",0,restartpass,&config_f);
277 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
278 ConfValue("die","value",0,DieValue,&config_f);
279 ConfValue("options","loglevel",0,dbg,&config_f);
280 ConfValue("options","netbuffersize",0,NB,&config_f);
281 ConfValue("options","maxwho",0,MW,&config_f);
282 ConfValue("options","allowhalfop",0,AH,&config_f);
283 ConfValue("options","allowprotect",0,AP,&config_f);
284 ConfValue("options","allowfounder",0,AF,&config_f);
285 ConfValue("dns","server",0,DNSServer,&config_f);
286 ConfValue("dns","timeout",0,DNT,&config_f);
287 ConfValue("options","moduledir",0,ModPath,&config_f);
288 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
290 NetBufferSize = atoi(NB);
291 MaxWhoResults = atoi(MW);
292 dns_timeout = atoi(DNT);
296 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
298 strlcpy(ModPath,MOD_PATH,MAXBUF);
299 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
300 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
301 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
302 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
304 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
305 NetBufferSize = 10240;
307 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
309 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
312 if (!strcmp(dbg,"debug"))
314 if (!strcmp(dbg,"verbose"))
316 if (!strcmp(dbg,"default"))
318 if (!strcmp(dbg,"sparse"))
320 if (!strcmp(dbg,"none"))
323 log(DEFAULT,"Reading message of the day...");
324 readfile(RULES,rules);
325 log(DEFAULT,"Reading connect classes...");
327 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
330 ConfValue("connect","allow",i,Value,&config_f);
331 ConfValue("connect","timeout",i,timeout,&config_f);
332 ConfValue("connect","flood",i,flood,&config_f);
333 ConfValue("connect","pingfreq",i,pfreq,&config_f);
334 ConfValue("connect","threshold",i,thold,&config_f);
335 ConfValue("connect","sendq",i,sqmax,&config_f);
336 ConfValue("connect","recvq",i,rqmax,&config_f);
339 strlcpy(c.host,Value,MAXBUF);
341 strlcpy(Value,"",MAXBUF);
342 ConfValue("connect","password",i,Value,&config_f);
343 strlcpy(c.pass,Value,MAXBUF);
344 c.registration_timeout = 90; // default is 2 minutes
346 c.flood = atoi(flood);
348 c.sendqmax = 262144; // 256k
349 c.recvqmax = 4096; // 4k
352 c.threshold = atoi(thold);
356 c.sendqmax = atoi(sqmax);
360 c.recvqmax = atoi(rqmax);
364 c.registration_timeout = atoi(timeout);
368 c.pingtime = atoi(pfreq);
370 Classes.push_back(c);
371 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);
375 ConfValue("connect","deny",i,Value,&config_f);
376 strlcpy(c.host,Value,MAXBUF);
378 Classes.push_back(c);
379 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
383 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
384 read_xline_defaults();
385 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
387 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
390 log(DEFAULT,"Adding and removing modules due to rehash...");
392 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
394 // store the old module names
395 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
397 old_module_names.push_back(*t);
400 // get the new module names
401 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
403 ConfValue("module","name",count2,Value,&config_f);
404 new_module_names.push_back(Value);
407 // now create a list of new modules that are due to be loaded
408 // and a seperate list of modules which are due to be unloaded
409 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
412 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
418 added_modules.push_back(*_new);
420 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
423 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
429 removed_modules.push_back(*oldm);
431 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
433 int rem = 0, add = 0;
434 if (!removed_modules.empty())
435 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
437 if (UnloadModule(removing->c_str()))
439 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
440 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
445 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
448 if (!added_modules.empty())
449 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
451 if (LoadModule(adding->c_str()))
453 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
454 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
459 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
462 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());
467 /* add a channel to a user, creating the record for it if needed and linking
468 * it to the user record */
470 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
472 if ((!user) || (!cn))
474 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
482 strncpy(cname,cn,MAXBUF);
484 // we MUST declare this wherever we use FOREACH_RESULT
487 if (strlen(cname) > CHANMAX-1)
489 cname[CHANMAX-1] = '\0';
492 log(DEBUG,"add_channel: %s %s",user->nick,cname);
494 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
496 return NULL; // already on the channel!
500 if (!FindChan(cname))
503 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
504 if (MOD_RESULT == 1) {
508 /* create a new one */
509 log(DEBUG,"add_channel: creating: %s",cname);
511 chanlist[cname] = new chanrec();
513 strlcpy(chanlist[cname]->name, cname,CHANMAX);
514 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
515 chanlist[cname]->created = TIME;
516 strcpy(chanlist[cname]->topic, "");
517 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
518 chanlist[cname]->topicset = 0;
519 Ptr = chanlist[cname];
520 log(DEBUG,"add_channel: created: %s",cname);
521 /* set created to 2 to indicate user
522 * is the first in the channel
523 * and should be given ops */
529 /* channel exists, just fish out a pointer to its struct */
530 Ptr = FindChan(cname);
533 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
535 // the override flag allows us to bypass channel modes
536 // and bans (used by servers)
537 if ((!override) || (!strcasecmp(user->server,ServerName)))
539 log(DEBUG,"Not overriding...");
541 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
542 if (MOD_RESULT == 1) {
545 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
549 log(DEBUG,"add_channel: checking key, invite, etc");
551 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
556 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
559 log(DEBUG,"add_channel: no key given in JOIN");
560 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
565 if (strcasecmp(key,Ptr->key))
567 log(DEBUG,"add_channel: bad key given in JOIN");
568 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
573 log(DEBUG,"add_channel: no key");
576 FOREACH_RESULT(OnCheckInvite(user, Ptr));
579 if (Ptr->binarymodes & CM_INVITEONLY)
581 log(DEBUG,"add_channel: channel is +i");
582 if (user->IsInvited(Ptr->name))
584 /* user was invited to channel */
585 /* there may be an optional channel NOTICE here */
589 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
593 log(DEBUG,"add_channel: channel is not +i");
596 FOREACH_RESULT(OnCheckLimit(user, Ptr));
601 if (usercount(Ptr) >= Ptr->limit)
603 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
608 log(DEBUG,"add_channel: about to walk banlist");
610 FOREACH_RESULT(OnCheckBan(user, Ptr));
613 /* check user against the channel banlist */
616 if (Ptr->bans.size())
618 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
620 if (match(user->GetFullHost(),i->data))
622 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
628 log(DEBUG,"add_channel: bans checked");
636 user->RemoveInvite(Ptr->name);
639 log(DEBUG,"add_channel: invites removed");
644 log(DEBUG,"Overridden checks");
652 log(DEBUG,"Passed channel checks");
654 for (int index =0; index != MAXCHANS; index++)
656 log(DEBUG,"Check location %d",index);
657 if (user->chans[index].channel == NULL)
659 log(DEBUG,"Adding into their channel list at location %d",index);
663 /* first user in is given ops */
664 user->chans[index].uc_modes = UCMODE_OP;
668 user->chans[index].uc_modes = 0;
670 user->chans[index].channel = Ptr;
671 Ptr->AddUser((char*)user);
672 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
674 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
676 // use the stamdard J token with no privilages.
680 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
684 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
686 NetSendToAll(buffer);
689 log(DEBUG,"Sent JOIN to client");
693 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
694 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
697 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
698 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
699 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
700 FOREACH_MOD OnUserJoin(user,Ptr);
704 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
705 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
709 /* remove a channel from a users record, and remove the record from memory
710 * if the channel has become empty */
712 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
714 if ((!user) || (!cname))
716 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
722 if ((!cname) || (!user))
727 Ptr = FindChan(cname);
734 FOREACH_MOD OnUserPart(user,Ptr);
735 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
737 for (int i =0; i != MAXCHANS; i++)
739 /* zap it from the channel list of the user */
740 if (user->chans[i].channel == Ptr)
744 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
749 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
750 NetSendToAll(buffer);
760 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
761 NetSendToAll(buffer);
764 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
766 user->chans[i].uc_modes = 0;
767 user->chans[i].channel = NULL;
768 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
773 Ptr->DelUser((char*)user);
775 /* if there are no users left on the channel */
778 chan_hash::iterator iter = chanlist.find(Ptr->name);
780 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
782 /* kill the record */
783 if (iter != chanlist.end())
785 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
787 chanlist.erase(iter);
793 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
795 if ((!src) || (!user) || (!Ptr) || (!reason))
797 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
801 if ((!Ptr) || (!user) || (!src))
806 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
808 if (!has_channel(user,Ptr))
810 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
815 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
816 if (MOD_RESULT == ACR_DENY)
819 if (MOD_RESULT == ACR_DEFAULT)
821 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
823 if (cstatus(src,Ptr) == STATUS_HOP)
825 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
829 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
837 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
841 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
843 for (int i =0; i != MAXCHANS; i++)
845 /* zap it from the channel list of the user */
846 if (user->chans[i].channel)
847 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
849 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
850 user->chans[i].uc_modes = 0;
851 user->chans[i].channel = NULL;
852 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
857 Ptr->DelUser((char*)user);
859 /* if there are no users left on the channel */
862 chan_hash::iterator iter = chanlist.find(Ptr->name);
864 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
866 /* kill the record */
867 if (iter != chanlist.end())
869 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
871 chanlist.erase(iter);
879 /* This function pokes and hacks at a parameter list like the following:
881 * PART #winbot,#darkgalaxy :m00!
883 * to turn it into a series of individual calls like this:
886 * PART #darkgalaxy :m00!
888 * The seperate calls are sent to a callback function provided by the caller
889 * (the caller will usually call itself recursively). The callback function
890 * must be a command handler. Calling this function on a line with no list causes
891 * no action to be taken. You must provide a starting and ending parameter number
892 * where the range of the list can be found, useful if you have a terminating
893 * parameter as above which is actually not part of the list, or parameters
894 * before the actual list as well. This code is used by many functions which
895 * can function as "one to list" (see the RFC) */
897 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
902 char blog[32][MAXBUF];
903 char blog2[32][MAXBUF];
904 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
908 for (int i = 0; i <32; i++)
911 for (int i = 0; i <32; i++)
915 for (int i = 0; i <10; i++)
924 if (pcnt > 1) /* we have a key to copy */
926 strlcpy(keystr,parameters[1],MAXBUF);
930 if (!parameters[start])
934 if (!strchr(parameters[start],','))
939 for (int i = start; i <= end; i++)
943 strlcat(plist,parameters[i],MAXBUF);
951 for (int i = 0; i < t; i++)
956 strlcpy(blog[j++],param,MAXBUF);
960 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
965 strlcpy(blog[j++],param,MAXBUF);
968 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
973 if ((joins) && (keystr))
975 if (strchr(keystr,','))
980 for (int i = 0; i < t2; i++)
982 if (keystr[i] == ',')
985 strlcpy(blog2[j++],param,MAXBUF);
989 strlcpy(blog2[j++],param,MAXBUF);
994 for (j = 0; j < total; j++)
1000 for (q = end; q < pcnt-1; q++)
1002 if (parameters[q+1])
1004 pars[q-end+1] = parameters[q+1];
1007 if ((joins) && (parameters[1]))
1018 /* repeatedly call the function with the hacked parameter list */
1019 if ((joins) && (pcnt > 1))
1023 // pars[1] already set up and containing key from blog2[j]
1028 pars[1] = parameters[1];
1034 fn(pars,pcnt-(end-start),u);
1043 void kill_link(userrec *user,const char* r)
1045 user_hash::iterator iter = clientlist.find(user->nick);
1047 char reason[MAXBUF];
1049 strncpy(reason,r,MAXBUF);
1051 if (strlen(reason)>MAXQUIT)
1053 reason[MAXQUIT-1] = '\0';
1056 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1057 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1058 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1060 if (user->registered == 7) {
1061 FOREACH_MOD OnUserQuit(user);
1062 WriteCommonExcept(user,"QUIT :%s",reason);
1064 // Q token must go to ALL servers!!!
1065 char buffer[MAXBUF];
1066 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1067 NetSendToAll(buffer);
1070 FOREACH_MOD OnUserDisconnect(user);
1074 FOREACH_MOD OnRawSocketClose(user->fd);
1077 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1078 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1081 log(DEBUG,"kqueue: Failed to remove user from queue!");
1084 shutdown(user->fd,2);
1088 if (user->registered == 7) {
1089 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1093 if (user->registered == 7) {
1094 purge_empty_chans(user);
1097 if (iter != clientlist.end())
1099 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1101 fd_ref_table[user->fd] = NULL;
1102 clientlist.erase(iter);
1107 void kill_link_silent(userrec *user,const char* r)
1109 user_hash::iterator iter = clientlist.find(user->nick);
1111 char reason[MAXBUF];
1113 strncpy(reason,r,MAXBUF);
1115 if (strlen(reason)>MAXQUIT)
1117 reason[MAXQUIT-1] = '\0';
1120 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1121 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1122 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1124 if (user->registered == 7) {
1125 FOREACH_MOD OnUserQuit(user);
1126 WriteCommonExcept(user,"QUIT :%s",reason);
1128 // Q token must go to ALL servers!!!
1129 char buffer[MAXBUF];
1130 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1131 NetSendToAll(buffer);
1134 FOREACH_MOD OnUserDisconnect(user);
1138 FOREACH_MOD OnRawSocketClose(user->fd);
1141 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1142 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1145 log(DEBUG,"kqueue: Failed to remove user from queue!");
1148 shutdown(user->fd,2);
1152 if (user->registered == 7) {
1153 purge_empty_chans(user);
1156 if (iter != clientlist.end())
1158 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1160 fd_ref_table[user->fd] = NULL;
1161 clientlist.erase(iter);
1167 int main(int argc, char** argv)
1171 log(DEBUG,"*** InspIRCd starting up!");
1172 if (!FileExists(CONFIG_FILE))
1174 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1175 log(DEFAULT,"main: no config");
1176 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1180 for (int i = 1; i < argc; i++)
1182 if (!strcmp(argv[i],"-nofork")) {
1185 if (!strcmp(argv[i],"-wait")) {
1188 if (!strcmp(argv[i],"-nolimit")) {
1193 strlcpy(MyExecutable,argv[0],MAXBUF);
1195 // initialize the lowercase mapping table
1196 for (int cn = 0; cn < 256; cn++)
1198 // lowercase the uppercase chars
1199 for (int cn = 65; cn < 91; cn++)
1200 lowermap[cn] = tolower(cn);
1201 // now replace the specific chars for scandanavian comparison
1202 lowermap['['] = '{';
1203 lowermap[']'] = '}';
1204 lowermap['\\'] = '|';
1206 if (InspIRCd(argv,argc) == ERROR)
1208 log(DEFAULT,"main: daemon function bailed");
1209 printf("ERROR: could not initialise. Shutting down.\n");
1216 template<typename T> inline string ConvToStr(const T &in)
1219 if (!(tmp << in)) return string();
1223 /* re-allocates a nick in the user_hash after they change nicknames,
1224 * returns a pointer to the new user as it may have moved */
1226 userrec* ReHashNick(char* Old, char* New)
1228 //user_hash::iterator newnick;
1229 user_hash::iterator oldnick = clientlist.find(Old);
1231 log(DEBUG,"ReHashNick: %s %s",Old,New);
1233 if (!strcasecmp(Old,New))
1235 log(DEBUG,"old nick is new nick, skipping");
1236 return oldnick->second;
1239 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1241 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1243 userrec* olduser = oldnick->second;
1244 clientlist[New] = olduser;
1245 clientlist.erase(oldnick);
1247 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1249 return clientlist[New];
1252 /* adds or updates an entry in the whowas list */
1253 void AddWhoWas(userrec* u)
1255 whowas_hash::iterator iter = whowas.find(u->nick);
1256 WhoWasUser *a = new WhoWasUser();
1257 strlcpy(a->nick,u->nick,NICKMAX);
1258 strlcpy(a->ident,u->ident,15);
1259 strlcpy(a->dhost,u->dhost,160);
1260 strlcpy(a->host,u->host,160);
1261 strlcpy(a->fullname,u->fullname,128);
1262 strlcpy(a->server,u->server,256);
1263 a->signon = u->signon;
1265 /* MAX_WHOWAS: max number of /WHOWAS items
1266 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1267 * can be replaced by a newer one
1270 if (iter == whowas.end())
1272 if (whowas.size() >= WHOWAS_MAX)
1274 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1276 // 3600 seconds in an hour ;)
1277 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1279 // delete the old one
1280 if (i->second) delete i->second;
1281 // replace with new one
1283 log(DEBUG,"added WHOWAS entry, purged an old record");
1287 // no space left and user doesnt exist. Don't leave ram in use!
1288 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1293 log(DEBUG,"added fresh WHOWAS entry");
1294 whowas[a->nick] = a;
1299 log(DEBUG,"updated WHOWAS entry");
1300 if (iter->second) delete iter->second;
1306 /* add a client connection to the sockets list */
1307 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1311 user_hash::iterator iter;
1313 tempnick = ConvToStr(socket) + "-unknown";
1314 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1316 iter = clientlist.find(tempnick);
1319 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1320 // using one as a registered connection. As theyre per fd, we can also safely assume
1321 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1322 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1323 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1324 // issue in earlier alphas/betas
1325 if (iter != clientlist.end())
1327 userrec* goner = iter->second;
1329 clientlist.erase(iter);
1333 * It is OK to access the value here this way since we know
1334 * it exists, we just created it above.
1336 * At NO other time should you access a value in a map or a
1337 * hash_map this way.
1339 clientlist[tempnick] = new userrec();
1341 NonBlocking(socket);
1342 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1344 clientlist[tempnick]->fd = socket;
1345 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1346 strncpy(clientlist[tempnick]->host, host,160);
1347 strncpy(clientlist[tempnick]->dhost, host,160);
1348 strncpy(clientlist[tempnick]->server, ServerName,256);
1349 strncpy(clientlist[tempnick]->ident, "unknown",15);
1350 clientlist[tempnick]->registered = 0;
1351 clientlist[tempnick]->signon = TIME+dns_timeout;
1352 clientlist[tempnick]->lastping = 1;
1353 clientlist[tempnick]->port = port;
1354 strncpy(clientlist[tempnick]->ip,ip,16);
1356 // set the registration timeout for this user
1357 unsigned long class_regtimeout = 90;
1358 int class_flood = 0;
1359 long class_threshold = 5;
1360 long class_sqmax = 262144; // 256kb
1361 long class_rqmax = 4096; // 4k
1363 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1365 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1367 class_regtimeout = (unsigned long)i->registration_timeout;
1368 class_flood = i->flood;
1369 clientlist[tempnick]->pingmax = i->pingtime;
1370 class_threshold = i->threshold;
1371 class_sqmax = i->sendqmax;
1372 class_rqmax = i->recvqmax;
1377 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1378 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1379 clientlist[tempnick]->flood = class_flood;
1380 clientlist[tempnick]->threshold = class_threshold;
1381 clientlist[tempnick]->sendqmax = class_sqmax;
1382 clientlist[tempnick]->recvqmax = class_rqmax;
1384 for (int i = 0; i < MAXCHANS; i++)
1386 clientlist[tempnick]->chans[i].channel = NULL;
1387 clientlist[tempnick]->chans[i].uc_modes = 0;
1390 if (clientlist.size() == MAXCLIENTS)
1392 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1396 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1397 // its a pretty big but for the moment valid assumption:
1398 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1399 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1400 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1401 // which for the time being is a physical impossibility (even the largest networks dont have more
1402 // than about 10,000 users on ONE server!)
1405 kill_link(clientlist[tempnick],"Server is full");
1410 char* e = matches_exception(ip);
1413 char* r = matches_zline(ip);
1416 char reason[MAXBUF];
1417 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1418 kill_link(clientlist[tempnick],reason);
1422 fd_ref_table[socket] = clientlist[tempnick];
1426 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1427 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1428 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1434 log(DEBUG,"kqueue: EACCES");
1437 log(DEBUG,"kqueue: EFAULT");
1440 log(DEBUG,"kqueue: EBADF=%d",ke.ident);
1443 log(DEBUG,"kqueue: EINTR");
1446 log(DEBUG,"kqueue: EINVAL");
1449 log(DEBUG,"kqueue: ENOENT");
1452 log(DEBUG,"kqueue: ENOMEM");
1455 log(DEBUG,"kqueue: ESRCH");
1458 log(DEBUG,"kqueue: UNKNOWN!");
1461 log(DEBUG,"kqueue: Failed to add user to queue!");
1467 /* shows the message of the day, and any other on-logon stuff */
1468 void FullConnectUser(userrec* user)
1471 user->idle_lastmsg = TIME;
1472 log(DEBUG,"ConnectUser: %s",user->nick);
1474 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1476 kill_link(user,"Invalid password");
1481 kill_link(user,"Unauthorised connection");
1485 char match_against[MAXBUF];
1486 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1487 char* e = matches_exception(match_against);
1490 char* r = matches_gline(match_against);
1493 char reason[MAXBUF];
1494 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1495 kill_link_silent(user,reason);
1498 r = matches_kline(user->host);
1501 char reason[MAXBUF];
1502 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1503 kill_link_silent(user,reason);
1508 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1509 user->registered = 7;
1511 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1512 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1513 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1514 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1515 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1516 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1517 std::stringstream v;
1518 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1519 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1520 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1522 std::string data005 = v.str();
1523 FOREACH_MOD On005Numeric(data005);
1524 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1525 // so i'd better split it :)
1526 std::stringstream out(data005);
1527 std::string token = "";
1528 std::string line5 = "";
1529 int token_counter = 0;
1533 line5 = line5 + token + " ";
1535 if ((token_counter >= 13) || (out.eof() == true))
1537 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1544 char buffer[MAXBUF];
1545 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);
1546 NetSendToAll(buffer);
1548 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1549 FOREACH_MOD OnUserConnect(user);
1550 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1554 /* shows the message of the day, and any other on-logon stuff */
1555 void ConnectUser(userrec *user)
1557 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1558 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1560 FullConnectUser(user);
1564 std::string GetVersionString()
1566 char Revision[] = "$Revision$";
1567 char versiondata[MAXBUF];
1568 char *s1 = Revision;
1570 char *v2 = strtok_r(s1," ",&savept);
1572 v2 = strtok_r(s1," ",&savept);
1575 char socketengine[] = "kqueue";
1577 char socketengine[] = "select";
1579 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1583 void handle_version(char **parameters, int pcnt, userrec *user)
1587 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1591 if (!strcmp(parameters[0],"*"))
1593 for (int j = 0; j < 32; j++)
1597 for (int x = 0; x < me[j]->connectors.size(); x++)
1599 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());
1605 if (match(ServerName,parameters[0]))
1607 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1610 bool displayed = false, found = false;
1611 for (int j = 0; j < 32; j++)
1615 for (int x = 0; x < me[j]->connectors.size(); x++)
1617 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1620 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1623 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1629 if ((!displayed) && (found))
1631 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1636 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1643 // calls a handler function for a command
1645 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1647 for (int i = 0; i < cmdlist.size(); i++)
1649 if (!strcasecmp(cmdlist[i].command,commandname))
1651 if (cmdlist[i].handler_function)
1653 if (pcnt>=cmdlist[i].min_params)
1655 if (strchr(user->modes,cmdlist[i].flags_needed))
1657 cmdlist[i].handler_function(parameters,pcnt,user);
1665 void DoSplitEveryone()
1667 bool go_again = true;
1671 for (int i = 0; i < 32; i++)
1675 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1677 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1680 j->CloseConnection();
1681 me[i]->connectors.erase(j);
1689 log(DEBUG,"Removed server. Will remove clients...");
1690 // iterate through the userlist and remove all users on this server.
1691 // because we're dealing with a mesh, we dont have to deal with anything
1692 // "down-route" from this server (nice huh)
1694 char reason[MAXBUF];
1698 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1700 if (strcasecmp(u->second->server,ServerName))
1702 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1703 kill_link(u->second,reason);
1713 void force_nickchange(userrec* user,const char* newnick)
1720 FOREACH_RESULT(OnUserPreNick(user,newnick));
1723 kill_link(user,"Nickname collision");
1726 if (matches_qline(newnick))
1729 kill_link(user,"Nickname collision");
1737 strncpy(nick,newnick,MAXBUF);
1739 if (user->registered == 7)
1743 handle_nick(pars,1,user);
1749 int process_parameters(char **command_p,char *parameters)
1752 int q = strlen(parameters);
1755 /* no parameters, command_p invalid! */
1758 if (parameters[0] == ':')
1760 command_p[0] = parameters+1;
1765 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1767 /* only one parameter */
1768 command_p[0] = parameters;
1769 if (parameters[0] == ':')
1771 if (strchr(parameters,' ') != NULL)
1779 command_p[j++] = parameters;
1780 for (int i = 0; i <= q; i++)
1782 if (parameters[i] == ' ')
1784 command_p[j++] = parameters+i+1;
1785 parameters[i] = '\0';
1786 if (command_p[j-1][0] == ':')
1788 *command_p[j-1]++; /* remove dodgy ":" */
1790 /* parameter like this marks end of the sequence */
1794 return j; /* returns total number of items in the list */
1797 void process_command(userrec *user, char* cmd)
1801 char *command_p[127];
1802 char p[MAXBUF], temp[MAXBUF];
1803 int j, items, cmd_found;
1805 for (int i = 0; i < 127; i++)
1806 command_p[i] = NULL;
1821 int total_params = 0;
1824 for (int q = 0; q < strlen(cmd)-1; q++)
1826 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1829 // found a 'trailing', we dont count them after this.
1837 // another phidjit bug...
1838 if (total_params > 126)
1840 *(strchr(cmd,' ')) = '\0';
1841 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1845 strlcpy(temp,cmd,MAXBUF);
1847 std::string tmp = cmd;
1848 for (int i = 0; i <= MODCOUNT; i++)
1850 std::string oldtmp = tmp;
1851 modules[i]->OnServerRaw(tmp,true,user);
1854 log(DEBUG,"A Module changed the input string!");
1855 log(DEBUG,"New string: %s",tmp.c_str());
1856 log(DEBUG,"Old string: %s",oldtmp.c_str());
1860 strlcpy(cmd,tmp.c_str(),MAXBUF);
1861 strlcpy(temp,cmd,MAXBUF);
1863 if (!strchr(cmd,' '))
1865 /* no parameters, lets skip the formalities and not chop up
1867 log(DEBUG,"About to preprocess command with no params");
1869 command_p[0] = NULL;
1871 for (int i = 0; i <= strlen(cmd); i++)
1873 cmd[i] = toupper(cmd[i]);
1881 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1882 for (int i = 0; i < strlen(temp); i++)
1884 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1890 /* split the full string into a command plus parameters */
1894 if (strchr(cmd,' '))
1896 for (int i = 0; i <= strlen(cmd); i++)
1898 /* capitalise the command ONLY, leave params intact */
1899 cmd[i] = toupper(cmd[i]);
1900 /* are we nearly there yet?! :P */
1904 parameters = cmd+i+1;
1912 for (int i = 0; i <= strlen(cmd); i++)
1914 cmd[i] = toupper(cmd[i]);
1921 if (strlen(command)>MAXCOMMAND)
1923 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1927 for (int x = 0; x < strlen(command); x++)
1929 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1931 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1933 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1936 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1943 for (int i = 0; i != cmdlist.size(); i++)
1945 if (cmdlist[i].command[0])
1947 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1953 items = process_parameters(command_p,parameters);
1958 command_p[0] = NULL;
1964 command_p[0] = NULL;
1969 /* activity resets the ping pending timer */
1970 user->nping = TIME + user->pingmax;
1971 if ((items) < cmdlist[i].min_params)
1973 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1974 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1977 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1979 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1980 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1984 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1986 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1987 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1991 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1993 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1995 if ((!isnick(user->nick)) || (user->registered != 7))
1997 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1998 WriteServ(user->fd,"451 %s :You have not registered",command);
2002 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2006 mycmd = strtok_r(DisabledCommands," ",&savept2);
2009 if (!strcasecmp(mycmd,command))
2011 // command is disabled!
2012 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2015 mycmd = strtok_r(NULL," ",&savept2);
2020 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2022 if (cmdlist[i].handler_function)
2025 /* ikky /stats counters */
2028 cmdlist[i].use_count++;
2029 cmdlist[i].total_bytes+=strlen(temp);
2033 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2034 if (MOD_RESULT == 1) {
2038 /* WARNING: nothing may come after the
2039 * command handler call, as the handler
2040 * may free the user structure! */
2042 cmdlist[i].handler_function(command_p,items,user);
2048 WriteServ(user->fd,"451 %s :You have not registered",command);
2056 if ((!cmd_found) && (user))
2059 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2063 bool removecommands(const char* source)
2065 bool go_again = true;
2069 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2071 if (!strcmp(i->source,source))
2073 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2084 void process_buffer(const char* cmdbuf,userrec *user)
2088 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2094 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2101 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2103 strlcpy(cmd,cmdbuf,MAXBUF);
2108 int sl = strlen(cmd)-1;
2109 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2114 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2119 while (cmd[sl] == ' ') // strip trailing spaces
2129 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2131 if ((user) && (cmd))
2133 process_command(user,cmd);
2137 void DoSync(serverrec* serv, char* tcp_host)
2140 log(DEBUG,"Sending sync");
2141 // send start of sync marker: Y <timestamp>
2142 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2143 // except the ones its receiving it from.
2144 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2145 serv->SendPacket(data,tcp_host);
2146 // send users and channels
2148 NetSendMyRoutingTable();
2150 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2151 for (int j = 0; j < 32; j++)
2155 for (int k = 0; k < me[j]->connectors.size(); k++)
2157 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2159 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2160 serv->SendPacket(data,tcp_host);
2166 // send our version for the remote side to cache
2167 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2168 serv->SendPacket(data,tcp_host);
2170 // sync the users and channels, give the modules a look-in.
2171 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2173 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);
2174 serv->SendPacket(data,tcp_host);
2175 if (strchr(u->second->modes,'o'))
2177 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2178 serv->SendPacket(data,tcp_host);
2180 for (int i = 0; i <= MODCOUNT; i++)
2182 string_list l = modules[i]->OnUserSync(u->second);
2183 for (int j = 0; j < l.size(); j++)
2185 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2186 serv->SendPacket(data,tcp_host);
2189 char* chl = chlist(u->second,u->second);
2192 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2193 serv->SendPacket(data,tcp_host);
2196 // send channel modes, topics etc...
2197 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2199 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2200 serv->SendPacket(data,tcp_host);
2201 for (int i = 0; i <= MODCOUNT; i++)
2203 string_list l = modules[i]->OnChannelSync(c->second);
2204 for (int j = 0; j < l.size(); j++)
2206 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2207 serv->SendPacket(data,tcp_host);
2210 if (c->second->topic[0])
2212 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);
2213 serv->SendPacket(data,tcp_host);
2215 // send current banlist
2217 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2219 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2220 serv->SendPacket(data,tcp_host);
2223 // sync global zlines, glines, etc
2224 sync_xlines(serv,tcp_host);
2226 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2227 serv->SendPacket(data,tcp_host);
2228 log(DEBUG,"Sent sync");
2229 // ircd sends its serverlist after the end of sync here
2233 void NetSendMyRoutingTable()
2235 // send out a line saying what is reachable to us.
2236 // E.g. if A is linked to B C and D, send out:
2238 // if its only linked to B and D send out:
2240 // if it has no links, dont even send out the line at all.
2241 char buffer[MAXBUF];
2242 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2243 bool sendit = false;
2244 for (int i = 0; i < 32; i++)
2248 for (int j = 0; j < me[i]->connectors.size(); j++)
2250 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2252 strlcat(buffer," ",MAXBUF);
2253 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2260 NetSendToAll(buffer);
2264 void DoSplit(const char* params)
2266 bool go_again = true;
2270 for (int i = 0; i < 32; i++)
2274 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2276 if (!strcasecmp(j->GetServerName().c_str(),params))
2279 j->CloseConnection();
2280 me[i]->connectors.erase(j);
2288 log(DEBUG,"Removed server. Will remove clients...");
2289 // iterate through the userlist and remove all users on this server.
2290 // because we're dealing with a mesh, we dont have to deal with anything
2291 // "down-route" from this server (nice huh)
2293 char reason[MAXBUF];
2294 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2298 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2300 if (!strcasecmp(u->second->server,params))
2302 kill_link(u->second,reason);
2310 // removes a server. Will NOT remove its users!
2312 void RemoveServer(const char* name)
2314 bool go_again = true;
2318 for (int i = 0; i < 32; i++)
2322 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2324 if (!strcasecmp(j->GetServerName().c_str(),name))
2327 j->CloseConnection();
2328 me[i]->connectors.erase(j);
2339 char MODERR[MAXBUF];
2346 void erase_factory(int j)
2349 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2354 factory.push_back(NULL);
2361 void erase_module(int j)
2364 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2370 modules.push_back(NULL);
2376 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2380 module_names.erase(v);
2388 bool UnloadModule(const char* filename)
2390 std::string filename_str = filename;
2391 for (int j = 0; j != module_names.size(); j++)
2393 if (module_names[j] == filename_str)
2395 if (modules[j]->GetVersion().Flags & VF_STATIC)
2397 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2398 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2402 log(DEBUG,"Deleting module...");
2404 log(DEBUG,"Erasing module entry...");
2406 log(DEBUG,"Removing dependent commands...");
2407 removecommands(filename);
2408 log(DEFAULT,"Module %s unloaded",filename);
2413 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2414 snprintf(MODERR,MAXBUF,"Module not loaded");
2418 bool LoadModule(const char* filename)
2420 char modfile[MAXBUF];
2421 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2422 std::string filename_str = filename;
2423 if (!DirValid(modfile))
2425 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2426 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2429 log(DEBUG,"Loading module: %s",modfile);
2430 if (FileExists(modfile))
2432 for (int j = 0; j < module_names.size(); j++)
2434 if (module_names[j] == filename_str)
2436 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2437 snprintf(MODERR,MAXBUF,"Module already loaded");
2441 ircd_module* a = new ircd_module(modfile);
2442 factory[MODCOUNT+1] = a;
2443 if (factory[MODCOUNT+1]->LastError())
2445 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2446 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2450 if (factory[MODCOUNT+1]->factory)
2452 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2453 modules[MODCOUNT+1] = m;
2454 /* save the module and the module's classfactory, if
2455 * this isnt done, random crashes can occur :/ */
2456 module_names.push_back(filename);
2460 log(DEFAULT,"Unable to load %s",modfile);
2461 snprintf(MODERR,MAXBUF,"Factory function failed!");
2467 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2468 snprintf(MODERR,MAXBUF,"Module file could not be found");
2475 int InspIRCd(char** argv, int argc)
2477 struct sockaddr_in client,server;
2478 char addrs[MAXBUF][255];
2479 int incomingSockfd, result = TRUE;
2482 int selectResult = 0, selectResult2 = 0;
2483 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2487 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2488 log_file = fopen(logpath.c_str(),"a+");
2491 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2494 printf("Logging to %s...\n",logpath.c_str());
2496 log(DEFAULT,"$Id$");
2499 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2501 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2503 SetupCommandTable();
2504 log(DEBUG,"InspIRCd: startup: default command table set up");
2506 ReadConfig(true,NULL);
2509 printf("WARNING: %s\n\n",DieValue);
2510 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2513 log(DEBUG,"InspIRCd: startup: read config");
2515 int clientportcount = 0, serverportcount = 0;
2517 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2519 ConfValue("bind","port",count,configToken,&config_f);
2520 ConfValue("bind","address",count,Addr,&config_f);
2521 ConfValue("bind","type",count,Type,&config_f);
2522 if (!strcmp(Type,"servers"))
2524 char Default[MAXBUF];
2525 strcpy(Default,"no");
2526 ConfValue("bind","default",count,Default,&config_f);
2527 if (strchr(Default,'y'))
2529 defaultRoute = serverportcount;
2530 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2532 me[serverportcount] = new serverrec(ServerName,100L,false);
2533 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2535 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2536 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2545 ports[clientportcount] = atoi(configToken);
2546 strlcpy(addrs[clientportcount],Addr,256);
2549 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2551 portCount = clientportcount;
2552 SERVERportCount = serverportcount;
2554 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2555 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2559 /* BugFix By Craig! :p */
2561 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2563 ConfValue("module","name",count,configToken,&config_f);
2564 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2565 if (!LoadModule(configToken))
2567 log(DEFAULT,"Exiting due to a module loader error.");
2568 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2572 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2574 startup_time = time(NULL);
2577 ConfValue("pid","file",0,PID,&config_f);
2578 // write once here, to try it out and make sure its ok
2581 /* setup select call */
2583 FD_ZERO(&selectFds);
2585 log(DEBUG,"InspIRCd: startup: zero selects");
2586 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2588 for (count = 0; count < portCount; count++)
2590 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2592 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2595 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2597 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2599 else /* well we at least bound to one socket so we'll continue */
2605 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2607 /* if we didn't bind to anything then abort */
2608 if (boundPortCount == 0)
2610 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2611 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2616 printf("\nInspIRCd is now running!\n");
2620 log(VERBOSE,"Not forking as -nofork was specified");
2624 if (DaemonSeed() == ERROR)
2626 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2627 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2632 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2637 if ((kq == -1) || (lkq == -1) || (skq == -1))
2639 log(DEFAULT,"main: kqueue() failed!");
2640 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2647 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2648 for (count = 0; count < boundPortCount; count++)
2651 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2652 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, 5, NULL);
2653 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2656 log(DEFAULT,"main: add listen ports to kqueue failed!");
2657 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2660 for (int t = 0; t != SERVERportCount; t++)
2665 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2666 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, 5, NULL);
2667 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2670 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2671 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2678 log(DEFAULT,"Using standard select socket engine.");
2683 length = sizeof (client);
2684 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2688 struct kevent ke_list[33];
2693 tvs.tv_usec = 10000L;
2696 tv.tv_usec = 10000L;
2700 tval.tv_usec = 10000L;
2702 int total_in_this_set = 0;
2703 int i = 0, v = 0, j = 0, cycle_iter = 0;
2704 bool expire_run = false;
2706 /* main loop, this never returns */
2709 #ifdef _POSIX_PRIORITY_SCHEDULING
2716 // we only read time() once per iteration rather than tons of times!
2722 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2723 // them in a list, then reap the list every second or so.
2724 if (((TIME % 5) == 0) && (!expire_run))
2727 FOREACH_MOD OnBackgroundTimer(TIME);
2731 if ((TIME % 5) == 1)
2734 // fix by brain - this must be below any manipulation of the hashmap by modules
2735 user_hash::iterator count2 = clientlist.begin();
2739 ts.tv_nsec = 30000L;
2740 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2743 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2744 for (int x = 0; x != SERVERportCount; x++)
2746 if ((me[x]) && (ke.ident == me[x]->fd))
2750 FD_ZERO(&serverfds);
2751 for (int x = 0; x != SERVERportCount; x++)
2754 FD_SET(me[x]->fd, &serverfds);
2756 tvs.tv_usec = 30000L;
2758 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
2761 for (int x = 0; x != SERVERportCount; x++)
2763 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2766 char remotehost[MAXBUF],resolved[MAXBUF];
2767 length = sizeof (client);
2768 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2769 if (incomingSockfd != -1)
2771 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2772 if(CleanAndResolve(resolved, remotehost) != TRUE)
2774 strlcpy(resolved,remotehost,MAXBUF);
2776 // add to this connections ircd_connector vector
2777 // *FIX* - we need the LOCAL port not the remote port in &client!
2778 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2784 for (int x = 0; x < SERVERportCount; x++)
2786 std::deque<std::string> msgs;
2787 std::deque<std::string> sums;
2790 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums)))
2792 for (int ctr = 0; ctr < msgs.size(); ctr++)
2794 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2795 strlcpy(tcp_sum,msgs[ctr].c_str(),MAXBUF);
2796 log(DEBUG,"Processing: %s",tcp_msg);
2799 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2802 // during a netburst, send all data to all other linked servers
2803 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2805 if (is_uline(tcp_host))
2807 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2809 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2813 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2815 std::string msg = tcp_msg;
2816 FOREACH_MOD OnPacketReceive(msg,tcp_host);
2817 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2818 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2824 while (count2 != clientlist.end())
2830 total_in_this_set = 0;
2832 user_hash::iterator xcount = count2;
2833 user_hash::iterator endingiter = count2;
2835 if (count2 == clientlist.end()) break;
2837 userrec* curr = NULL;
2840 curr = count2->second;
2842 if ((curr) && (curr->fd != 0))
2844 #ifdef _POSIX_PRIORITY_SCHEDULING
2847 // assemble up to 64 sockets into an fd_set
2848 // to implement a pooling mechanism.
2850 // This should be up to 64x faster than the
2851 // old implementation.
2853 while (total_in_this_set < 1024)
2855 if (count2 != clientlist.end())
2857 curr = count2->second;
2858 // we don't check the state of remote users.
2859 if ((curr->fd != -1) && (curr->fd != FD_MAGIC_NUMBER))
2861 curr->FlushWriteBuf();
2862 if (curr->GetWriteError() != "")
2864 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2865 kill_link(curr,curr->GetWriteError().c_str());
2869 FD_SET (curr->fd, &sfd);
2871 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2872 // their connection class.
2873 if ((TIME > curr->timeout) && (curr->registered != 7))
2875 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2876 kill_link(curr,"Registration timeout");
2879 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2881 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
2882 curr->dns_done = true;
2884 FullConnectUser(curr);
2887 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
2889 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2890 FullConnectUser(curr);
2893 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2895 if ((!curr->lastping) && (curr->registered == 7))
2897 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2898 kill_link(curr,"Ping timeout");
2901 Write(curr->fd,"PING :%s",ServerName);
2902 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2904 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2908 total_in_this_set++;
2912 endingiter = count2;
2913 count2 = xcount; // roll back to where we were
2915 // KQUEUE: We don't go through a loop to fill the fd_set so instead we must manually do this loop every now and again.
2916 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
2918 if (cycle_iter > 10) while (count2 != clientlist.end())
2921 if (count2 != clientlist.end())
2923 curr = count2->second;
2924 // we don't check the state of remote users.
2925 if ((curr->fd != -1) && (curr->fd != FD_MAGIC_NUMBER))
2928 curr->FlushWriteBuf();
2929 if (curr->GetWriteError() != "")
2931 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2932 kill_link(curr,curr->GetWriteError().c_str());
2936 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2937 // their connection class.
2938 if ((TIME > curr->timeout) && (curr->registered != 7))
2940 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2941 kill_link(curr,"Registration timeout");
2944 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2946 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
2947 curr->dns_done = true;
2949 FullConnectUser(curr);
2952 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2954 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2955 FullConnectUser(curr);
2958 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2960 if ((!curr->lastping) && (curr->registered == 7))
2962 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2963 kill_link(curr,"Ping timeout");
2966 Write(curr->fd,"PING :%s",ServerName);
2967 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2969 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2976 // increment the counter right to the end of the list, as kqueue processes everything in one go
2984 // for now, we only read 1 event. We could read soooo many more :)
2985 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
2988 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
2989 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
2990 userrec* cu = fd_ref_table[ke.ident];
2992 tval.tv_usec = 1000L;
2993 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
2995 // now loop through all of the items in this pool if any are waiting
2996 if (selectResult2 > 0)
2997 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
2999 // SELECT: we have to iterate...
3000 userrec* cu = count2a->second;
3003 #ifdef _POSIX_PRIORITY_SCHEDULING
3008 // KQUEUE: We already know we have a valid FD. No checks needed.
3009 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3011 // SELECT: We don't know if our FD is valid.
3012 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3015 log(DEBUG,"Data waiting on socket %d",cu->fd);
3018 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3021 result = read(cu->fd, data, 65535);
3023 else result = result2;
3024 log(DEBUG,"Read result: %d",result);
3027 statsRecv += result;
3028 // perform a check on the raw buffer as an array (not a string!) to remove
3029 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3030 // hopefully this should stop even more people whining about "Unknown command: *"
3031 for (int checker = 0; checker < result; checker++)
3033 if ((data[checker] == 0) || (data[checker] == 7))
3034 data[checker] = ' ';
3037 data[result] = '\0';
3038 userrec* current = cu;
3039 int currfd = current->fd;
3041 // add the data to the users buffer
3043 if (!current->AddBuffer(data))
3045 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3046 if (current->registered == 7)
3048 kill_link(current,"RecvQ exceeded");
3052 WriteOpers("*** Excess flood from %s",current->ip);
3053 log(DEFAULT,"Excess flood from: %s",current->ip);
3054 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3059 if (current->recvq.length() > NetBufferSize)
3061 if (current->registered == 7)
3063 kill_link(current,"RecvQ exceeded");
3067 WriteOpers("*** Excess flood from %s",current->ip);
3068 log(DEFAULT,"Excess flood from: %s",current->ip);
3069 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3074 // while there are complete lines to process...
3075 while (current->BufferIsReady())
3078 if (TIME > current->reset_due)
3080 current->reset_due = TIME + current->threshold;
3081 current->lines_in = 0;
3083 current->lines_in++;
3084 if (current->lines_in > current->flood)
3086 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3087 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3088 kill_link(current,"Excess flood");
3091 if ((floodlines > current->flood) && (current->flood != 0))
3093 if (current->registered == 7)
3095 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3096 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3097 kill_link(current,"Excess flood");
3101 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3106 char sanitized[MAXBUF];
3107 // use GetBuffer to copy single lines into the sanitized string
3108 std::string single_line = current->GetBuffer();
3109 current->bytes_in += single_line.length();
3111 if (single_line.length()>512)
3113 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3114 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3115 kill_link(current,"Excess flood");
3118 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3121 userrec* old_comp = fd_ref_table[currfd];
3122 // we're gonna re-scan to check if the nick is gone, after every
3123 // command - if it has, we're gonna bail
3124 process_buffer(sanitized,current);
3125 // look for the user's record in case it's changed... if theyve quit,
3126 // we cant do anything more with their buffer, so bail.
3127 // there used to be an ugly, slow loop here. Now we have a reference
3128 // table, life is much easier (and FASTER)
3129 userrec* new_comp = fd_ref_table[currfd];
3130 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3138 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3140 log(DEBUG,"killing: %s",cu->nick);
3141 kill_link(cu,strerror(errno));
3145 // result EAGAIN means nothing read
3146 if (result == EAGAIN)
3156 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3157 kill_link(cu,"Client exited");
3158 // must bail here? kill_link removes the hash, corrupting the iterator
3159 log(DEBUG,"Bailing from client exit");
3165 else if (result > 0)
3170 for (int q = 0; q < total_in_this_set; q++)
3176 #ifdef _POSIX_PRIORITY_SCHEDULING
3181 // set up select call
3182 for (count = 0; count < boundPortCount; count++)
3184 FD_SET (openSockfd[count], &selectFds);
3187 tv.tv_usec = 30000L;
3188 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3190 /* select is reporting a waiting socket. Poll them all to find out which */
3191 if (selectResult > 0)
3193 for (count = 0; count < boundPortCount; count++)
3195 if (FD_ISSET (openSockfd[count], &selectFds))
3199 ts.tv_nsec = 30000L;
3200 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3201 if (i > 0) for (j = 0; j < i; j++)
3203 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke.ident);
3204 // this isnt as efficient as it could be, we could create a reference table
3205 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3206 // number of listening ports on the average ircd is a small number (less than 20)
3207 // compared to the number of clients (possibly over 2000)
3208 for (count = 0; count < boundPortCount; count++)
3210 if (ke_list[j].ident == openSockfd[count])
3213 char target[MAXBUF], resolved[MAXBUF];
3214 length = sizeof (client);
3215 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3217 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3218 strlcpy (resolved, target, MAXBUF);
3220 if (incomingSockfd < 0)
3222 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3223 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3228 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3230 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3231 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3239 #ifdef _POSIX_PRIORITY_SCHEDULING
3245 close (incomingSockfd);