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>
38 #include <ext/hash_map>
47 #include "connection.h"
59 #include "inspstring.h"
61 #include "helperfuncs.h"
64 int LogLevel = DEFAULT;
65 char ServerName[MAXBUF];
67 char ServerDesc[MAXBUF];
68 char AdminName[MAXBUF];
69 char AdminEmail[MAXBUF];
70 char AdminNick[MAXBUF];
72 char restartpass[MAXBUF];
76 char PrefixQuit[MAXBUF];
77 char DieValue[MAXBUF];
78 char DNSServer[MAXBUF];
80 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
81 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
83 time_t startup_time = time(NULL);
84 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
85 extern int MaxWhoResults;
89 char DisabledCommands[MAXBUF];
91 bool AllowHalfop = true;
92 bool AllowProtect = true;
93 bool AllowFounder = true;
95 extern std::vector<Module*, __single_client_alloc> modules;
96 std::vector<std::string, __single_client_alloc> module_names;
97 extern std::vector<ircd_module*, __single_client_alloc> factory;
100 int openSockfd[MAXSOCKS];
102 bool unlimitcore = false;
104 time_t TIME = time(NULL), OLDTIME = time(NULL);
110 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp, __single_client_alloc> user_hash;
111 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp, __single_client_alloc> chan_hash;
112 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp, __single_client_alloc> address_cache;
113 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp, __single_client_alloc> whowas_hash;
114 typedef std::deque<command_t, __single_client_alloc> command_table;
116 // This table references users by file descriptor.
117 // its an array to make it VERY fast, as all lookups are referenced
118 // by an integer, meaning there is no need for a scan/search operation.
119 userrec* fd_ref_table[65536];
121 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
127 user_hash clientlist;
130 command_table cmdlist;
137 struct linger linger = { 0 };
138 char MyExecutable[1024];
139 int boundPortCount = 0;
140 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
141 int defaultRoute = 0;
142 char ModPath[MAXBUF];
146 int has_channel(userrec *u, chanrec *c);
147 int usercount(chanrec *c);
148 int usercount_i(chanrec *c);
149 char* Passwd(userrec *user);
150 bool IsDenied(userrec *user);
151 void AddWhoWas(userrec* u);
153 std::vector<long> auth_cookies;
154 std::stringstream config_f(stringstream::in | stringstream::out);
156 std::vector<userrec*, __single_client_alloc> all_opers;
160 void AddOper(userrec* user)
162 log(DEBUG,"Oper added to optimization list");
163 all_opers.push_back(user);
166 void DeleteOper(userrec* user)
168 for (std::vector<userrec*, __single_client_alloc>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
172 log(DEBUG,"Oper removed from optimization list");
181 char Revision[] = "$Revision$";
184 char *v2 = strtok_r(s1," ",&savept);
186 v2 = strtok_r(s1," ",&savept);
188 return (long)(atof(v2)*10000);
192 std::string getservername()
197 std::string getserverdesc()
202 std::string getnetworkname()
207 std::string getadminname()
212 std::string getadminemail()
217 std::string getadminnick()
222 void ReadConfig(bool bail, userrec* user)
224 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
225 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
227 std::stringstream errstr;
229 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
234 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
242 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
243 while (!errstr.eof())
245 errstr.getline(dataline,1024);
246 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
251 WriteOpers("There were errors in the configuration file:",user->nick);
252 while (!errstr.eof())
254 errstr.getline(dataline,1024);
255 WriteOpers(dataline);
262 ConfValue("server","name",0,ServerName,&config_f);
263 ConfValue("server","description",0,ServerDesc,&config_f);
264 ConfValue("server","network",0,Network,&config_f);
265 ConfValue("admin","name",0,AdminName,&config_f);
266 ConfValue("admin","email",0,AdminEmail,&config_f);
267 ConfValue("admin","nick",0,AdminNick,&config_f);
268 ConfValue("files","motd",0,motd,&config_f);
269 ConfValue("files","rules",0,rules,&config_f);
270 ConfValue("power","diepass",0,diepass,&config_f);
271 ConfValue("power","pause",0,pauseval,&config_f);
272 ConfValue("power","restartpass",0,restartpass,&config_f);
273 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
274 ConfValue("die","value",0,DieValue,&config_f);
275 ConfValue("options","loglevel",0,dbg,&config_f);
276 ConfValue("options","netbuffersize",0,NB,&config_f);
277 ConfValue("options","maxwho",0,MW,&config_f);
278 ConfValue("options","allowhalfop",0,AH,&config_f);
279 ConfValue("options","allowprotect",0,AP,&config_f);
280 ConfValue("options","allowfounder",0,AF,&config_f);
281 ConfValue("dns","server",0,DNSServer,&config_f);
282 ConfValue("dns","timeout",0,DNT,&config_f);
283 ConfValue("options","moduledir",0,ModPath,&config_f);
284 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
286 NetBufferSize = atoi(NB);
287 MaxWhoResults = atoi(MW);
288 dns_timeout = atoi(DNT);
292 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
294 strlcpy(ModPath,MOD_PATH,MAXBUF);
295 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
296 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
297 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
298 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
300 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
301 NetBufferSize = 10240;
303 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
305 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
308 if (!strcmp(dbg,"debug"))
310 if (!strcmp(dbg,"verbose"))
312 if (!strcmp(dbg,"default"))
314 if (!strcmp(dbg,"sparse"))
316 if (!strcmp(dbg,"none"))
319 log(DEFAULT,"Reading message of the day...");
320 readfile(RULES,rules);
321 log(DEFAULT,"Reading connect classes...");
323 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
326 ConfValue("connect","allow",i,Value,&config_f);
327 ConfValue("connect","timeout",i,timeout,&config_f);
328 ConfValue("connect","flood",i,flood,&config_f);
329 ConfValue("connect","pingfreq",i,pfreq,&config_f);
330 ConfValue("connect","threshold",i,thold,&config_f);
331 ConfValue("connect","sendq",i,sqmax,&config_f);
332 ConfValue("connect","recvq",i,rqmax,&config_f);
335 strlcpy(c.host,Value,MAXBUF);
337 strlcpy(Value,"",MAXBUF);
338 ConfValue("connect","password",i,Value,&config_f);
339 strlcpy(c.pass,Value,MAXBUF);
340 c.registration_timeout = 90; // default is 2 minutes
342 c.flood = atoi(flood);
344 c.sendqmax = 262144; // 256k
345 c.recvqmax = 4096; // 4k
348 c.threshold = atoi(thold);
352 c.sendqmax = atoi(sqmax);
356 c.recvqmax = atoi(rqmax);
360 c.registration_timeout = atoi(timeout);
364 c.pingtime = atoi(pfreq);
366 Classes.push_back(c);
367 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);
371 ConfValue("connect","deny",i,Value,&config_f);
372 strlcpy(c.host,Value,MAXBUF);
374 Classes.push_back(c);
375 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
379 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
380 read_xline_defaults();
381 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
383 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
386 log(DEFAULT,"Adding and removing modules due to rehash...");
388 std::vector<std::string, __single_client_alloc> old_module_names, new_module_names, added_modules, removed_modules;
390 // store the old module names
391 for (std::vector<std::string, __single_client_alloc>::iterator t = module_names.begin(); t != module_names.end(); t++)
393 old_module_names.push_back(*t);
396 // get the new module names
397 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
399 ConfValue("module","name",count2,Value,&config_f);
400 new_module_names.push_back(Value);
403 // now create a list of new modules that are due to be loaded
404 // and a seperate list of modules which are due to be unloaded
405 for (std::vector<std::string, __single_client_alloc>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
408 for (std::vector<std::string, __single_client_alloc>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
414 added_modules.push_back(*_new);
416 for (std::vector<std::string, __single_client_alloc>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
419 for (std::vector<std::string, __single_client_alloc>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
425 removed_modules.push_back(*oldm);
427 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
429 int rem = 0, add = 0;
430 if (!removed_modules.empty())
431 for (std::vector<std::string, __single_client_alloc>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
433 if (UnloadModule(removing->c_str()))
435 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
436 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
441 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
444 if (!added_modules.empty())
445 for (std::vector<std::string, __single_client_alloc>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
447 if (LoadModule(adding->c_str()))
449 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
450 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
455 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
458 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());
463 /* add a channel to a user, creating the record for it if needed and linking
464 * it to the user record */
466 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
468 if ((!user) || (!cn))
470 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
478 strncpy(cname,cn,MAXBUF);
480 // we MUST declare this wherever we use FOREACH_RESULT
483 if (strlen(cname) > CHANMAX-1)
485 cname[CHANMAX-1] = '\0';
488 log(DEBUG,"add_channel: %s %s",user->nick,cname);
490 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
492 return NULL; // already on the channel!
496 if (!FindChan(cname))
499 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
500 if (MOD_RESULT == 1) {
504 /* create a new one */
505 log(DEBUG,"add_channel: creating: %s",cname);
507 chanlist[cname] = new chanrec();
509 strlcpy(chanlist[cname]->name, cname,CHANMAX);
510 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
511 chanlist[cname]->created = TIME;
512 strcpy(chanlist[cname]->topic, "");
513 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
514 chanlist[cname]->topicset = 0;
515 Ptr = chanlist[cname];
516 log(DEBUG,"add_channel: created: %s",cname);
517 /* set created to 2 to indicate user
518 * is the first in the channel
519 * and should be given ops */
525 /* channel exists, just fish out a pointer to its struct */
526 Ptr = FindChan(cname);
529 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
531 // the override flag allows us to bypass channel modes
532 // and bans (used by servers)
533 if ((!override) || (!strcasecmp(user->server,ServerName)))
535 log(DEBUG,"Not overriding...");
537 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
538 if (MOD_RESULT == 1) {
541 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
545 log(DEBUG,"add_channel: checking key, invite, etc");
547 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
552 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
555 log(DEBUG,"add_channel: no key given in JOIN");
556 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
561 if (strcasecmp(key,Ptr->key))
563 log(DEBUG,"add_channel: bad key given in JOIN");
564 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
569 log(DEBUG,"add_channel: no key");
572 FOREACH_RESULT(OnCheckInvite(user, Ptr));
575 if (Ptr->binarymodes & CM_INVITEONLY)
577 log(DEBUG,"add_channel: channel is +i");
578 if (user->IsInvited(Ptr->name))
580 /* user was invited to channel */
581 /* there may be an optional channel NOTICE here */
585 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
589 log(DEBUG,"add_channel: channel is not +i");
592 FOREACH_RESULT(OnCheckLimit(user, Ptr));
597 if (usercount(Ptr) >= Ptr->limit)
599 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
604 log(DEBUG,"add_channel: about to walk banlist");
606 FOREACH_RESULT(OnCheckBan(user, Ptr));
609 /* check user against the channel banlist */
612 if (Ptr->bans.size())
614 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
616 if (match(user->GetFullHost(),i->data))
618 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
624 log(DEBUG,"add_channel: bans checked");
632 user->RemoveInvite(Ptr->name);
635 log(DEBUG,"add_channel: invites removed");
640 log(DEBUG,"Overridden checks");
648 log(DEBUG,"Passed channel checks");
650 for (int index =0; index != MAXCHANS; index++)
652 log(DEBUG,"Check location %d",index);
653 if (user->chans[index].channel == NULL)
655 log(DEBUG,"Adding into their channel list at location %d",index);
659 /* first user in is given ops */
660 user->chans[index].uc_modes = UCMODE_OP;
664 user->chans[index].uc_modes = 0;
666 user->chans[index].channel = Ptr;
667 Ptr->AddUser((char*)user);
668 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
670 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
672 // use the stamdard J token with no privilages.
676 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
680 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
682 NetSendToAll(buffer);
685 log(DEBUG,"Sent JOIN to client");
689 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
690 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
693 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
694 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
695 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
696 FOREACH_MOD OnUserJoin(user,Ptr);
700 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
701 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
705 /* remove a channel from a users record, and remove the record from memory
706 * if the channel has become empty */
708 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
710 if ((!user) || (!cname))
712 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
718 if ((!cname) || (!user))
723 Ptr = FindChan(cname);
730 FOREACH_MOD OnUserPart(user,Ptr);
731 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
733 for (int i =0; i != MAXCHANS; i++)
735 /* zap it from the channel list of the user */
736 if (user->chans[i].channel == Ptr)
740 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
745 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
746 NetSendToAll(buffer);
756 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
757 NetSendToAll(buffer);
760 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
762 user->chans[i].uc_modes = 0;
763 user->chans[i].channel = NULL;
764 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
769 Ptr->DelUser((char*)user);
771 /* if there are no users left on the channel */
774 chan_hash::iterator iter = chanlist.find(Ptr->name);
776 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
778 /* kill the record */
779 if (iter != chanlist.end())
781 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
783 chanlist.erase(iter);
789 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
791 if ((!src) || (!user) || (!Ptr) || (!reason))
793 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
797 if ((!Ptr) || (!user) || (!src))
802 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
804 if (!has_channel(user,Ptr))
806 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
811 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
812 if (MOD_RESULT == ACR_DENY)
815 if (MOD_RESULT == ACR_DEFAULT)
817 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
819 if (cstatus(src,Ptr) == STATUS_HOP)
821 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
825 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
833 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
837 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
839 for (int i =0; i != MAXCHANS; i++)
841 /* zap it from the channel list of the user */
842 if (user->chans[i].channel)
843 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
845 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
846 user->chans[i].uc_modes = 0;
847 user->chans[i].channel = NULL;
848 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
853 Ptr->DelUser((char*)user);
855 /* if there are no users left on the channel */
858 chan_hash::iterator iter = chanlist.find(Ptr->name);
860 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
862 /* kill the record */
863 if (iter != chanlist.end())
865 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
867 chanlist.erase(iter);
875 /* This function pokes and hacks at a parameter list like the following:
877 * PART #winbot,#darkgalaxy :m00!
879 * to turn it into a series of individual calls like this:
882 * PART #darkgalaxy :m00!
884 * The seperate calls are sent to a callback function provided by the caller
885 * (the caller will usually call itself recursively). The callback function
886 * must be a command handler. Calling this function on a line with no list causes
887 * no action to be taken. You must provide a starting and ending parameter number
888 * where the range of the list can be found, useful if you have a terminating
889 * parameter as above which is actually not part of the list, or parameters
890 * before the actual list as well. This code is used by many functions which
891 * can function as "one to list" (see the RFC) */
893 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
898 char blog[32][MAXBUF];
899 char blog2[32][MAXBUF];
900 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
904 for (int i = 0; i <32; i++)
907 for (int i = 0; i <32; i++)
911 for (int i = 0; i <10; i++)
920 if (pcnt > 1) /* we have a key to copy */
922 strlcpy(keystr,parameters[1],MAXBUF);
926 if (!parameters[start])
930 if (!strchr(parameters[start],','))
935 for (int i = start; i <= end; i++)
939 strlcat(plist,parameters[i],MAXBUF);
947 for (int i = 0; i < t; i++)
952 strlcpy(blog[j++],param,MAXBUF);
956 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
961 strlcpy(blog[j++],param,MAXBUF);
964 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
969 if ((joins) && (keystr))
971 if (strchr(keystr,','))
976 for (int i = 0; i < t2; i++)
978 if (keystr[i] == ',')
981 strlcpy(blog2[j++],param,MAXBUF);
985 strlcpy(blog2[j++],param,MAXBUF);
990 for (j = 0; j < total; j++)
996 for (q = end; q < pcnt-1; q++)
1000 pars[q-end+1] = parameters[q+1];
1003 if ((joins) && (parameters[1]))
1014 /* repeatedly call the function with the hacked parameter list */
1015 if ((joins) && (pcnt > 1))
1019 // pars[1] already set up and containing key from blog2[j]
1024 pars[1] = parameters[1];
1030 fn(pars,pcnt-(end-start),u);
1039 void kill_link(userrec *user,const char* r)
1041 user_hash::iterator iter = clientlist.find(user->nick);
1043 char reason[MAXBUF];
1045 strncpy(reason,r,MAXBUF);
1047 if (strlen(reason)>MAXQUIT)
1049 reason[MAXQUIT-1] = '\0';
1052 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1053 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1054 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1056 if (user->registered == 7) {
1057 FOREACH_MOD OnUserQuit(user);
1058 WriteCommonExcept(user,"QUIT :%s",reason);
1060 // Q token must go to ALL servers!!!
1061 char buffer[MAXBUF];
1062 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1063 NetSendToAll(buffer);
1066 FOREACH_MOD OnUserDisconnect(user);
1070 FOREACH_MOD OnRawSocketClose(user->fd);
1073 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1074 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1077 log(DEBUG,"kqueue: Failed to remove user from queue!");
1080 shutdown(user->fd,2);
1084 if (user->registered == 7) {
1085 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1089 if (user->registered == 7) {
1090 purge_empty_chans(user);
1093 if (iter != clientlist.end())
1095 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1097 fd_ref_table[user->fd] = NULL;
1098 clientlist.erase(iter);
1103 void kill_link_silent(userrec *user,const char* r)
1105 user_hash::iterator iter = clientlist.find(user->nick);
1107 char reason[MAXBUF];
1109 strncpy(reason,r,MAXBUF);
1111 if (strlen(reason)>MAXQUIT)
1113 reason[MAXQUIT-1] = '\0';
1116 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1117 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1118 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1120 if (user->registered == 7) {
1121 FOREACH_MOD OnUserQuit(user);
1122 WriteCommonExcept(user,"QUIT :%s",reason);
1124 // Q token must go to ALL servers!!!
1125 char buffer[MAXBUF];
1126 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1127 NetSendToAll(buffer);
1130 FOREACH_MOD OnUserDisconnect(user);
1134 FOREACH_MOD OnRawSocketClose(user->fd);
1137 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1138 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1141 log(DEBUG,"kqueue: Failed to remove user from queue!");
1144 shutdown(user->fd,2);
1148 if (user->registered == 7) {
1149 purge_empty_chans(user);
1152 if (iter != clientlist.end())
1154 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1156 fd_ref_table[user->fd] = NULL;
1157 clientlist.erase(iter);
1163 int main(int argc, char** argv)
1167 log(DEBUG,"*** InspIRCd starting up!");
1168 if (!FileExists(CONFIG_FILE))
1170 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1171 log(DEFAULT,"main: no config");
1172 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1176 for (int i = 1; i < argc; i++)
1178 if (!strcmp(argv[i],"-nofork")) {
1181 if (!strcmp(argv[i],"-wait")) {
1184 if (!strcmp(argv[i],"-nolimit")) {
1189 strlcpy(MyExecutable,argv[0],MAXBUF);
1191 // initialize the lowercase mapping table
1192 for (int cn = 0; cn < 256; cn++)
1194 // lowercase the uppercase chars
1195 for (int cn = 65; cn < 91; cn++)
1196 lowermap[cn] = tolower(cn);
1197 // now replace the specific chars for scandanavian comparison
1198 lowermap['['] = '{';
1199 lowermap[']'] = '}';
1200 lowermap['\\'] = '|';
1202 if (InspIRCd(argv,argc) == ERROR)
1204 log(DEFAULT,"main: daemon function bailed");
1205 printf("ERROR: could not initialise. Shutting down.\n");
1212 template<typename T> inline string ConvToStr(const T &in)
1215 if (!(tmp << in)) return string();
1219 /* re-allocates a nick in the user_hash after they change nicknames,
1220 * returns a pointer to the new user as it may have moved */
1222 userrec* ReHashNick(char* Old, char* New)
1224 //user_hash::iterator newnick;
1225 user_hash::iterator oldnick = clientlist.find(Old);
1227 log(DEBUG,"ReHashNick: %s %s",Old,New);
1229 if (!strcasecmp(Old,New))
1231 log(DEBUG,"old nick is new nick, skipping");
1232 return oldnick->second;
1235 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1237 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1239 userrec* olduser = oldnick->second;
1240 clientlist[New] = olduser;
1241 clientlist.erase(oldnick);
1243 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1245 return clientlist[New];
1248 /* adds or updates an entry in the whowas list */
1249 void AddWhoWas(userrec* u)
1251 whowas_hash::iterator iter = whowas.find(u->nick);
1252 WhoWasUser *a = new WhoWasUser();
1253 strlcpy(a->nick,u->nick,NICKMAX);
1254 strlcpy(a->ident,u->ident,15);
1255 strlcpy(a->dhost,u->dhost,160);
1256 strlcpy(a->host,u->host,160);
1257 strlcpy(a->fullname,u->fullname,128);
1258 strlcpy(a->server,u->server,256);
1259 a->signon = u->signon;
1261 /* MAX_WHOWAS: max number of /WHOWAS items
1262 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1263 * can be replaced by a newer one
1266 if (iter == whowas.end())
1268 if (whowas.size() >= WHOWAS_MAX)
1270 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1272 // 3600 seconds in an hour ;)
1273 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1275 // delete the old one
1276 if (i->second) delete i->second;
1277 // replace with new one
1279 log(DEBUG,"added WHOWAS entry, purged an old record");
1283 // no space left and user doesnt exist. Don't leave ram in use!
1284 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1289 log(DEBUG,"added fresh WHOWAS entry");
1290 whowas[a->nick] = a;
1295 log(DEBUG,"updated WHOWAS entry");
1296 if (iter->second) delete iter->second;
1302 /* add a client connection to the sockets list */
1303 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1307 user_hash::iterator iter;
1309 tempnick = ConvToStr(socket) + "-unknown";
1310 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1312 iter = clientlist.find(tempnick);
1315 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1316 // using one as a registered connection. As theyre per fd, we can also safely assume
1317 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1318 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1319 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1320 // issue in earlier alphas/betas
1321 if (iter != clientlist.end())
1323 userrec* goner = iter->second;
1325 clientlist.erase(iter);
1329 * It is OK to access the value here this way since we know
1330 * it exists, we just created it above.
1332 * At NO other time should you access a value in a map or a
1333 * hash_map this way.
1335 clientlist[tempnick] = new userrec();
1337 NonBlocking(socket);
1338 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1340 clientlist[tempnick]->fd = socket;
1341 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1342 strncpy(clientlist[tempnick]->host, host,160);
1343 strncpy(clientlist[tempnick]->dhost, host,160);
1344 strncpy(clientlist[tempnick]->server, ServerName,256);
1345 strncpy(clientlist[tempnick]->ident, "unknown",15);
1346 clientlist[tempnick]->registered = 0;
1347 clientlist[tempnick]->signon = TIME+dns_timeout;
1348 clientlist[tempnick]->lastping = 1;
1349 clientlist[tempnick]->port = port;
1350 strncpy(clientlist[tempnick]->ip,ip,16);
1352 // set the registration timeout for this user
1353 unsigned long class_regtimeout = 90;
1354 int class_flood = 0;
1355 long class_threshold = 5;
1356 long class_sqmax = 262144; // 256kb
1357 long class_rqmax = 4096; // 4k
1359 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1361 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1363 class_regtimeout = (unsigned long)i->registration_timeout;
1364 class_flood = i->flood;
1365 clientlist[tempnick]->pingmax = i->pingtime;
1366 class_threshold = i->threshold;
1367 class_sqmax = i->sendqmax;
1368 class_rqmax = i->recvqmax;
1373 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1374 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1375 clientlist[tempnick]->flood = class_flood;
1376 clientlist[tempnick]->threshold = class_threshold;
1377 clientlist[tempnick]->sendqmax = class_sqmax;
1378 clientlist[tempnick]->recvqmax = class_rqmax;
1380 for (int i = 0; i < MAXCHANS; i++)
1382 clientlist[tempnick]->chans[i].channel = NULL;
1383 clientlist[tempnick]->chans[i].uc_modes = 0;
1386 if (clientlist.size() == MAXCLIENTS)
1388 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1392 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1393 // its a pretty big but for the moment valid assumption:
1394 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1395 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1396 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1397 // which for the time being is a physical impossibility (even the largest networks dont have more
1398 // than about 10,000 users on ONE server!)
1401 kill_link(clientlist[tempnick],"Server is full");
1406 char* e = matches_exception(ip);
1409 char* r = matches_zline(ip);
1412 char reason[MAXBUF];
1413 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1414 kill_link(clientlist[tempnick],reason);
1418 fd_ref_table[socket] = clientlist[tempnick];
1422 log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1423 EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1424 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1430 log(DEBUG,"kqueue: EACCES");
1433 log(DEBUG,"kqueue: EFAULT");
1436 log(DEBUG,"kqueue: EBADF=%d",ke.ident);
1439 log(DEBUG,"kqueue: EINTR");
1442 log(DEBUG,"kqueue: EINVAL");
1445 log(DEBUG,"kqueue: ENOENT");
1448 log(DEBUG,"kqueue: ENOMEM");
1451 log(DEBUG,"kqueue: ESRCH");
1454 log(DEBUG,"kqueue: UNKNOWN!");
1457 log(DEBUG,"kqueue: Failed to add user to queue!");
1463 /* shows the message of the day, and any other on-logon stuff */
1464 void FullConnectUser(userrec* user)
1467 user->idle_lastmsg = TIME;
1468 log(DEBUG,"ConnectUser: %s",user->nick);
1470 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1472 kill_link(user,"Invalid password");
1477 kill_link(user,"Unauthorised connection");
1481 char match_against[MAXBUF];
1482 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1483 char* e = matches_exception(match_against);
1486 char* r = matches_gline(match_against);
1489 char reason[MAXBUF];
1490 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1491 kill_link_silent(user,reason);
1494 r = matches_kline(user->host);
1497 char reason[MAXBUF];
1498 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1499 kill_link_silent(user,reason);
1504 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1505 user->registered = 7;
1507 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1508 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1509 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1510 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1511 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1512 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1513 std::stringstream v;
1514 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1515 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1516 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1518 std::string data005 = v.str();
1519 FOREACH_MOD On005Numeric(data005);
1520 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1521 // so i'd better split it :)
1522 std::stringstream out(data005);
1523 std::string token = "";
1524 std::string line5 = "";
1525 int token_counter = 0;
1529 line5 = line5 + token + " ";
1531 if ((token_counter >= 13) || (out.eof() == true))
1533 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1540 char buffer[MAXBUF];
1541 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);
1542 NetSendToAll(buffer);
1544 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1545 FOREACH_MOD OnUserConnect(user);
1546 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1550 /* shows the message of the day, and any other on-logon stuff */
1551 void ConnectUser(userrec *user)
1553 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1554 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1556 FullConnectUser(user);
1560 std::string GetVersionString()
1562 char Revision[] = "$Revision$";
1563 char versiondata[MAXBUF];
1564 char *s1 = Revision;
1566 char *v2 = strtok_r(s1," ",&savept);
1568 v2 = strtok_r(s1," ",&savept);
1571 char socketengine[] = "kqueue";
1573 char socketengine[] = "select";
1575 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1579 void handle_version(char **parameters, int pcnt, userrec *user)
1583 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1587 if (!strcmp(parameters[0],"*"))
1589 for (int j = 0; j < 32; j++)
1593 for (int x = 0; x < me[j]->connectors.size(); x++)
1595 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());
1601 if (match(ServerName,parameters[0]))
1603 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1606 bool displayed = false, found = false;
1607 for (int j = 0; j < 32; j++)
1611 for (int x = 0; x < me[j]->connectors.size(); x++)
1613 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1616 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1619 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1625 if ((!displayed) && (found))
1627 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1632 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1639 // calls a handler function for a command
1641 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1643 for (int i = 0; i < cmdlist.size(); i++)
1645 if (!strcasecmp(cmdlist[i].command,commandname))
1647 if (cmdlist[i].handler_function)
1649 if (pcnt>=cmdlist[i].min_params)
1651 if (strchr(user->modes,cmdlist[i].flags_needed))
1653 cmdlist[i].handler_function(parameters,pcnt,user);
1661 void DoSplitEveryone()
1663 bool go_again = true;
1667 for (int i = 0; i < 32; i++)
1671 for (vector<ircd_connector, __single_client_alloc>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1673 if (strcasecmp(j->GetServerName().c_str(),ServerName))
1676 j->CloseConnection();
1677 me[i]->connectors.erase(j);
1685 log(DEBUG,"Removed server. Will remove clients...");
1686 // iterate through the userlist and remove all users on this server.
1687 // because we're dealing with a mesh, we dont have to deal with anything
1688 // "down-route" from this server (nice huh)
1690 char reason[MAXBUF];
1694 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1696 if (strcasecmp(u->second->server,ServerName))
1698 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1699 kill_link(u->second,reason);
1709 void force_nickchange(userrec* user,const char* newnick)
1716 FOREACH_RESULT(OnUserPreNick(user,newnick));
1719 kill_link(user,"Nickname collision");
1722 if (matches_qline(newnick))
1725 kill_link(user,"Nickname collision");
1733 strncpy(nick,newnick,MAXBUF);
1735 if (user->registered == 7)
1739 handle_nick(pars,1,user);
1745 int process_parameters(char **command_p,char *parameters)
1748 int q = strlen(parameters);
1751 /* no parameters, command_p invalid! */
1754 if (parameters[0] == ':')
1756 command_p[0] = parameters+1;
1761 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1763 /* only one parameter */
1764 command_p[0] = parameters;
1765 if (parameters[0] == ':')
1767 if (strchr(parameters,' ') != NULL)
1775 command_p[j++] = parameters;
1776 for (int i = 0; i <= q; i++)
1778 if (parameters[i] == ' ')
1780 command_p[j++] = parameters+i+1;
1781 parameters[i] = '\0';
1782 if (command_p[j-1][0] == ':')
1784 *command_p[j-1]++; /* remove dodgy ":" */
1786 /* parameter like this marks end of the sequence */
1790 return j; /* returns total number of items in the list */
1793 void process_command(userrec *user, char* cmd)
1797 char *command_p[127];
1798 char p[MAXBUF], temp[MAXBUF];
1799 int j, items, cmd_found;
1801 for (int i = 0; i < 127; i++)
1802 command_p[i] = NULL;
1817 int total_params = 0;
1820 for (int q = 0; q < strlen(cmd)-1; q++)
1822 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1825 // found a 'trailing', we dont count them after this.
1833 // another phidjit bug...
1834 if (total_params > 126)
1836 *(strchr(cmd,' ')) = '\0';
1837 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1841 strlcpy(temp,cmd,MAXBUF);
1843 std::string tmp = cmd;
1844 for (int i = 0; i <= MODCOUNT; i++)
1846 std::string oldtmp = tmp;
1847 modules[i]->OnServerRaw(tmp,true,user);
1850 log(DEBUG,"A Module changed the input string!");
1851 log(DEBUG,"New string: %s",tmp.c_str());
1852 log(DEBUG,"Old string: %s",oldtmp.c_str());
1856 strlcpy(cmd,tmp.c_str(),MAXBUF);
1857 strlcpy(temp,cmd,MAXBUF);
1859 if (!strchr(cmd,' '))
1861 /* no parameters, lets skip the formalities and not chop up
1863 log(DEBUG,"About to preprocess command with no params");
1865 command_p[0] = NULL;
1867 for (int i = 0; i <= strlen(cmd); i++)
1869 cmd[i] = toupper(cmd[i]);
1877 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1878 for (int i = 0; i < strlen(temp); i++)
1880 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1886 /* split the full string into a command plus parameters */
1890 if (strchr(cmd,' '))
1892 for (int i = 0; i <= strlen(cmd); i++)
1894 /* capitalise the command ONLY, leave params intact */
1895 cmd[i] = toupper(cmd[i]);
1896 /* are we nearly there yet?! :P */
1900 parameters = cmd+i+1;
1908 for (int i = 0; i <= strlen(cmd); i++)
1910 cmd[i] = toupper(cmd[i]);
1917 if (strlen(command)>MAXCOMMAND)
1919 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1923 for (int x = 0; x < strlen(command); x++)
1925 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1927 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1929 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1932 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1939 for (int i = 0; i != cmdlist.size(); i++)
1941 if (cmdlist[i].command[0])
1943 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1949 items = process_parameters(command_p,parameters);
1954 command_p[0] = NULL;
1960 command_p[0] = NULL;
1965 /* activity resets the ping pending timer */
1966 user->nping = TIME + user->pingmax;
1967 if ((items) < cmdlist[i].min_params)
1969 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1970 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1973 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1975 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1976 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1980 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1982 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1983 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1987 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1989 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1991 if ((!isnick(user->nick)) || (user->registered != 7))
1993 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1994 WriteServ(user->fd,"451 %s :You have not registered",command);
1998 if ((user->registered == 7) && (!strchr(user->modes,'o')))
2002 mycmd = strtok_r(DisabledCommands," ",&savept2);
2005 if (!strcasecmp(mycmd,command))
2007 // command is disabled!
2008 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2011 mycmd = strtok_r(NULL," ",&savept2);
2016 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2018 if (cmdlist[i].handler_function)
2021 /* ikky /stats counters */
2024 cmdlist[i].use_count++;
2025 cmdlist[i].total_bytes+=strlen(temp);
2029 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2030 if (MOD_RESULT == 1) {
2034 /* WARNING: nothing may come after the
2035 * command handler call, as the handler
2036 * may free the user structure! */
2038 cmdlist[i].handler_function(command_p,items,user);
2044 WriteServ(user->fd,"451 %s :You have not registered",command);
2052 if ((!cmd_found) && (user))
2055 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2059 bool removecommands(const char* source)
2061 bool go_again = true;
2065 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2067 if (!strcmp(i->source,source))
2069 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2080 void process_buffer(const char* cmdbuf,userrec *user)
2084 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2090 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2097 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2099 strlcpy(cmd,cmdbuf,MAXBUF);
2104 int sl = strlen(cmd)-1;
2105 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2110 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2115 while (cmd[sl] == ' ') // strip trailing spaces
2125 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2127 if ((user) && (cmd))
2129 process_command(user,cmd);
2133 void DoSync(serverrec* serv, char* tcp_host)
2136 log(DEBUG,"Sending sync");
2137 // send start of sync marker: Y <timestamp>
2138 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2139 // except the ones its receiving it from.
2140 snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2141 serv->SendPacket(data,tcp_host);
2142 // send users and channels
2144 NetSendMyRoutingTable();
2146 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2147 for (int j = 0; j < 32; j++)
2151 for (int k = 0; k < me[j]->connectors.size(); k++)
2153 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2155 snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2156 serv->SendPacket(data,tcp_host);
2162 // send our version for the remote side to cache
2163 snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2164 serv->SendPacket(data,tcp_host);
2166 // sync the users and channels, give the modules a look-in.
2167 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2169 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);
2170 serv->SendPacket(data,tcp_host);
2171 if (strchr(u->second->modes,'o'))
2173 snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2174 serv->SendPacket(data,tcp_host);
2176 for (int i = 0; i <= MODCOUNT; i++)
2178 string_list l = modules[i]->OnUserSync(u->second);
2179 for (int j = 0; j < l.size(); j++)
2181 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2182 serv->SendPacket(data,tcp_host);
2185 char* chl = chlist(u->second,u->second);
2188 snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2189 serv->SendPacket(data,tcp_host);
2192 // send channel modes, topics etc...
2193 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2195 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2196 serv->SendPacket(data,tcp_host);
2197 for (int i = 0; i <= MODCOUNT; i++)
2199 string_list l = modules[i]->OnChannelSync(c->second);
2200 for (int j = 0; j < l.size(); j++)
2202 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2203 serv->SendPacket(data,tcp_host);
2206 if (c->second->topic[0])
2208 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);
2209 serv->SendPacket(data,tcp_host);
2211 // send current banlist
2213 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2215 snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2216 serv->SendPacket(data,tcp_host);
2219 // sync global zlines, glines, etc
2220 sync_xlines(serv,tcp_host);
2222 snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2223 serv->SendPacket(data,tcp_host);
2224 log(DEBUG,"Sent sync");
2225 // ircd sends its serverlist after the end of sync here
2229 void NetSendMyRoutingTable()
2231 // send out a line saying what is reachable to us.
2232 // E.g. if A is linked to B C and D, send out:
2234 // if its only linked to B and D send out:
2236 // if it has no links, dont even send out the line at all.
2237 char buffer[MAXBUF];
2238 snprintf(buffer,MAXBUF,"$ %s",ServerName);
2239 bool sendit = false;
2240 for (int i = 0; i < 32; i++)
2244 for (int j = 0; j < me[i]->connectors.size(); j++)
2246 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2248 strlcat(buffer," ",MAXBUF);
2249 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2256 NetSendToAll(buffer);
2260 void DoSplit(const char* params)
2262 bool go_again = true;
2266 for (int i = 0; i < 32; i++)
2270 for (vector<ircd_connector, __single_client_alloc>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2272 if (!strcasecmp(j->GetServerName().c_str(),params))
2275 j->CloseConnection();
2276 me[i]->connectors.erase(j);
2284 log(DEBUG,"Removed server. Will remove clients...");
2285 // iterate through the userlist and remove all users on this server.
2286 // because we're dealing with a mesh, we dont have to deal with anything
2287 // "down-route" from this server (nice huh)
2289 char reason[MAXBUF];
2290 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2294 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2296 if (!strcasecmp(u->second->server,params))
2298 kill_link(u->second,reason);
2306 // removes a server. Will NOT remove its users!
2308 void RemoveServer(const char* name)
2310 bool go_again = true;
2314 for (int i = 0; i < 32; i++)
2318 for (vector<ircd_connector, __single_client_alloc>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2320 if (!strcasecmp(j->GetServerName().c_str(),name))
2323 j->CloseConnection();
2324 me[i]->connectors.erase(j);
2335 char MODERR[MAXBUF];
2342 void erase_factory(int j)
2345 for (std::vector<ircd_module*, __single_client_alloc>::iterator t = factory.begin(); t != factory.end(); t++)
2350 factory.push_back(NULL);
2357 void erase_module(int j)
2360 for (std::vector<Module*, __single_client_alloc>::iterator m = modules.begin(); m!= modules.end(); m++)
2366 modules.push_back(NULL);
2372 for (std::vector<std::string, __single_client_alloc>::iterator v = module_names.begin(); v != module_names.end(); v++)
2376 module_names.erase(v);
2384 bool UnloadModule(const char* filename)
2386 std::string filename_str = filename;
2387 for (int j = 0; j != module_names.size(); j++)
2389 if (module_names[j] == filename_str)
2391 if (modules[j]->GetVersion().Flags & VF_STATIC)
2393 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2394 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2398 log(DEBUG,"Deleting module...");
2400 log(DEBUG,"Erasing module entry...");
2402 log(DEBUG,"Removing dependent commands...");
2403 removecommands(filename);
2404 log(DEFAULT,"Module %s unloaded",filename);
2409 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2410 snprintf(MODERR,MAXBUF,"Module not loaded");
2414 bool LoadModule(const char* filename)
2416 char modfile[MAXBUF];
2417 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2418 std::string filename_str = filename;
2419 if (!DirValid(modfile))
2421 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2422 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2425 log(DEBUG,"Loading module: %s",modfile);
2426 if (FileExists(modfile))
2428 for (int j = 0; j < module_names.size(); j++)
2430 if (module_names[j] == filename_str)
2432 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2433 snprintf(MODERR,MAXBUF,"Module already loaded");
2437 ircd_module* a = new ircd_module(modfile);
2438 factory[MODCOUNT+1] = a;
2439 if (factory[MODCOUNT+1]->LastError())
2441 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2442 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2446 if (factory[MODCOUNT+1]->factory)
2448 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2449 modules[MODCOUNT+1] = m;
2450 /* save the module and the module's classfactory, if
2451 * this isnt done, random crashes can occur :/ */
2452 module_names.push_back(filename);
2456 log(DEFAULT,"Unable to load %s",modfile);
2457 snprintf(MODERR,MAXBUF,"Factory function failed!");
2463 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2464 snprintf(MODERR,MAXBUF,"Module file could not be found");
2471 int InspIRCd(char** argv, int argc)
2473 struct sockaddr_in client,server;
2474 char addrs[MAXBUF][255];
2475 int incomingSockfd, result = TRUE;
2478 int selectResult = 0, selectResult2 = 0;
2479 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2483 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2484 log_file = fopen(logpath.c_str(),"a+");
2487 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2490 printf("Logging to %s...\n",logpath.c_str());
2492 log(DEFAULT,"$Id$");
2495 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2497 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2499 SetupCommandTable();
2500 log(DEBUG,"InspIRCd: startup: default command table set up");
2502 ReadConfig(true,NULL);
2505 printf("WARNING: %s\n\n",DieValue);
2506 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2509 log(DEBUG,"InspIRCd: startup: read config");
2511 int clientportcount = 0, serverportcount = 0;
2513 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2515 ConfValue("bind","port",count,configToken,&config_f);
2516 ConfValue("bind","address",count,Addr,&config_f);
2517 ConfValue("bind","type",count,Type,&config_f);
2518 if (!strcmp(Type,"servers"))
2520 char Default[MAXBUF];
2521 strcpy(Default,"no");
2522 ConfValue("bind","default",count,Default,&config_f);
2523 if (strchr(Default,'y'))
2525 defaultRoute = serverportcount;
2526 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2528 me[serverportcount] = new serverrec(ServerName,100L,false);
2529 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2531 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2532 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2541 ports[clientportcount] = atoi(configToken);
2542 strlcpy(addrs[clientportcount],Addr,256);
2545 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2547 portCount = clientportcount;
2548 SERVERportCount = serverportcount;
2550 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2551 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2555 /* BugFix By Craig! :p */
2557 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2559 ConfValue("module","name",count,configToken,&config_f);
2560 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2561 if (!LoadModule(configToken))
2563 log(DEFAULT,"Exiting due to a module loader error.");
2564 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2568 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2570 startup_time = time(NULL);
2573 ConfValue("pid","file",0,PID,&config_f);
2574 // write once here, to try it out and make sure its ok
2577 /* setup select call */
2579 FD_ZERO(&selectFds);
2581 log(DEBUG,"InspIRCd: startup: zero selects");
2582 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2584 for (count = 0; count < portCount; count++)
2586 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2588 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2591 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2593 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2595 else /* well we at least bound to one socket so we'll continue */
2601 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2603 /* if we didn't bind to anything then abort */
2604 if (boundPortCount == 0)
2606 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2607 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2612 printf("\nInspIRCd is now running!\n");
2616 log(VERBOSE,"Not forking as -nofork was specified");
2620 if (DaemonSeed() == ERROR)
2622 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2623 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2628 // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2633 if ((kq == -1) || (lkq == -1) || (skq == -1))
2635 log(DEFAULT,"main: kqueue() failed!");
2636 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2643 log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2644 for (count = 0; count < boundPortCount; count++)
2647 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2648 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, 5, NULL);
2649 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2652 log(DEFAULT,"main: add listen ports to kqueue failed!");
2653 printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2656 for (int t = 0; t != SERVERportCount; t++)
2661 log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2662 EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, 5, NULL);
2663 int i = kevent(skq, &ke, 1, 0, 0, NULL);
2666 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2667 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2674 log(DEFAULT,"Using standard select socket engine.");
2679 length = sizeof (client);
2680 char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2684 struct kevent ke_list[33];
2689 tvs.tv_usec = 10000L;
2692 tv.tv_usec = 10000L;
2696 tval.tv_usec = 10000L;
2698 int total_in_this_set = 0;
2699 int i = 0, v = 0, j = 0, cycle_iter = 0;
2700 bool expire_run = false;
2702 /* main loop, this never returns */
2705 #ifdef _POSIX_PRIORITY_SCHEDULING
2712 // we only read time() once per iteration rather than tons of times!
2718 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2719 // them in a list, then reap the list every second or so.
2720 if (((TIME % 5) == 0) && (!expire_run))
2723 FOREACH_MOD OnBackgroundTimer(TIME);
2727 if ((TIME % 5) == 1)
2730 // fix by brain - this must be below any manipulation of the hashmap by modules
2731 user_hash::iterator count2 = clientlist.begin();
2735 ts.tv_nsec = 30000L;
2736 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2739 log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2740 for (int x = 0; x != SERVERportCount; x++)
2742 if ((me[x]) && (ke.ident == me[x]->fd))
2746 FD_ZERO(&serverfds);
2747 for (int x = 0; x != SERVERportCount; x++)
2750 FD_SET(me[x]->fd, &serverfds);
2752 tvs.tv_usec = 30000L;
2754 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
2757 for (int x = 0; x != SERVERportCount; x++)
2759 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2762 char remotehost[MAXBUF],resolved[MAXBUF];
2763 length = sizeof (client);
2764 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2765 if (incomingSockfd != -1)
2767 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2768 if(CleanAndResolve(resolved, remotehost) != TRUE)
2770 strlcpy(resolved,remotehost,MAXBUF);
2772 // add to this connections ircd_connector vector
2773 // *FIX* - we need the LOCAL port not the remote port in &client!
2774 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2780 for (int x = 0; x < SERVERportCount; x++)
2782 std::deque<std::string> msgs;
2783 std::deque<std::string> sums;
2786 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums)))
2788 for (int ctr = 0; ctr < msgs.size(); ctr++)
2790 strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2791 strlcpy(tcp_sum,msgs[ctr].c_str(),MAXBUF);
2792 log(DEBUG,"Processing: %s",tcp_msg);
2795 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2798 // during a netburst, send all data to all other linked servers
2799 if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2801 if (is_uline(tcp_host))
2803 if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2805 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2809 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2811 std::string msg = tcp_msg;
2812 FOREACH_MOD OnPacketReceive(msg,tcp_host);
2813 strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2814 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2820 while (count2 != clientlist.end())
2826 total_in_this_set = 0;
2828 user_hash::iterator xcount = count2;
2829 user_hash::iterator endingiter = count2;
2831 if (count2 == clientlist.end()) break;
2833 userrec* curr = NULL;
2836 curr = count2->second;
2838 if ((curr) && (curr->fd != 0))
2840 #ifdef _POSIX_PRIORITY_SCHEDULING
2843 // assemble up to 64 sockets into an fd_set
2844 // to implement a pooling mechanism.
2846 // This should be up to 64x faster than the
2847 // old implementation.
2849 while (total_in_this_set < 1024)
2851 if (count2 != clientlist.end())
2853 curr = count2->second;
2854 // we don't check the state of remote users.
2855 if ((curr->fd != -1) && (curr->fd != FD_MAGIC_NUMBER))
2857 curr->FlushWriteBuf();
2858 if (curr->GetWriteError() != "")
2860 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2861 kill_link(curr,curr->GetWriteError().c_str());
2865 FD_SET (curr->fd, &sfd);
2867 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2868 // their connection class.
2869 if ((TIME > curr->timeout) && (curr->registered != 7))
2871 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2872 kill_link(curr,"Registration timeout");
2875 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2877 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
2878 curr->dns_done = true;
2880 FullConnectUser(curr);
2883 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
2885 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2886 FullConnectUser(curr);
2889 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2891 if ((!curr->lastping) && (curr->registered == 7))
2893 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2894 kill_link(curr,"Ping timeout");
2897 Write(curr->fd,"PING :%s",ServerName);
2898 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2900 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2904 total_in_this_set++;
2908 endingiter = count2;
2909 count2 = xcount; // roll back to where we were
2911 // 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.
2912 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
2914 if (cycle_iter > 10) while (count2 != clientlist.end())
2917 if (count2 != clientlist.end())
2919 curr = count2->second;
2920 // we don't check the state of remote users.
2921 if ((curr->fd != -1) && (curr->fd != FD_MAGIC_NUMBER))
2924 curr->FlushWriteBuf();
2925 if (curr->GetWriteError() != "")
2927 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2928 kill_link(curr,curr->GetWriteError().c_str());
2932 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2933 // their connection class.
2934 if ((TIME > curr->timeout) && (curr->registered != 7))
2936 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2937 kill_link(curr,"Registration timeout");
2940 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2942 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
2943 curr->dns_done = true;
2945 FullConnectUser(curr);
2948 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2950 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2951 FullConnectUser(curr);
2954 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2956 if ((!curr->lastping) && (curr->registered == 7))
2958 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2959 kill_link(curr,"Ping timeout");
2962 Write(curr->fd,"PING :%s",ServerName);
2963 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2965 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2972 // increment the counter right to the end of the list, as kqueue processes everything in one go
2980 // for now, we only read 1 event. We could read soooo many more :)
2981 int i = kevent(kq, NULL, 0, &ke, 1, &ts);
2984 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
2985 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
2986 userrec* cu = fd_ref_table[ke.ident];
2988 tval.tv_usec = 1000L;
2989 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
2991 // now loop through all of the items in this pool if any are waiting
2992 if (selectResult2 > 0)
2993 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
2995 // SELECT: we have to iterate...
2996 userrec* cu = count2a->second;
2999 #ifdef _POSIX_PRIORITY_SCHEDULING
3004 // KQUEUE: We already know we have a valid FD. No checks needed.
3005 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3007 // SELECT: We don't know if our FD is valid.
3008 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3011 log(DEBUG,"Data waiting on socket %d",cu->fd);
3014 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3017 result = read(cu->fd, data, 65535);
3019 else result = result2;
3020 log(DEBUG,"Read result: %d",result);
3023 statsRecv += result;
3024 // perform a check on the raw buffer as an array (not a string!) to remove
3025 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3026 // hopefully this should stop even more people whining about "Unknown command: *"
3027 for (int checker = 0; checker < result; checker++)
3029 if ((data[checker] == 0) || (data[checker] == 7))
3030 data[checker] = ' ';
3033 data[result] = '\0';
3034 userrec* current = cu;
3035 int currfd = current->fd;
3037 // add the data to the users buffer
3039 if (!current->AddBuffer(data))
3041 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3042 if (current->registered == 7)
3044 kill_link(current,"RecvQ exceeded");
3048 WriteOpers("*** Excess flood from %s",current->ip);
3049 log(DEFAULT,"Excess flood from: %s",current->ip);
3050 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3055 if (current->recvq.length() > NetBufferSize)
3057 if (current->registered == 7)
3059 kill_link(current,"RecvQ exceeded");
3063 WriteOpers("*** Excess flood from %s",current->ip);
3064 log(DEFAULT,"Excess flood from: %s",current->ip);
3065 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3070 // while there are complete lines to process...
3071 while (current->BufferIsReady())
3074 if (TIME > current->reset_due)
3076 current->reset_due = TIME + current->threshold;
3077 current->lines_in = 0;
3079 current->lines_in++;
3080 if (current->lines_in > current->flood)
3082 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3083 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3084 kill_link(current,"Excess flood");
3087 if ((floodlines > current->flood) && (current->flood != 0))
3089 if (current->registered == 7)
3091 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3092 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3093 kill_link(current,"Excess flood");
3097 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3102 char sanitized[MAXBUF];
3103 // use GetBuffer to copy single lines into the sanitized string
3104 std::string single_line = current->GetBuffer();
3105 current->bytes_in += single_line.length();
3107 if (single_line.length()>512)
3109 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3110 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3111 kill_link(current,"Excess flood");
3114 strlcpy(sanitized,single_line.c_str(),MAXBUF);
3117 userrec* old_comp = fd_ref_table[currfd];
3118 // we're gonna re-scan to check if the nick is gone, after every
3119 // command - if it has, we're gonna bail
3120 process_buffer(sanitized,current);
3121 // look for the user's record in case it's changed... if theyve quit,
3122 // we cant do anything more with their buffer, so bail.
3123 // there used to be an ugly, slow loop here. Now we have a reference
3124 // table, life is much easier (and FASTER)
3125 userrec* new_comp = fd_ref_table[currfd];
3126 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3134 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3136 log(DEBUG,"killing: %s",cu->nick);
3137 kill_link(cu,strerror(errno));
3141 // result EAGAIN means nothing read
3142 if (result == EAGAIN)
3152 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3153 kill_link(cu,"Client exited");
3154 // must bail here? kill_link removes the hash, corrupting the iterator
3155 log(DEBUG,"Bailing from client exit");
3161 else if (result > 0)
3166 for (int q = 0; q < total_in_this_set; q++)
3172 #ifdef _POSIX_PRIORITY_SCHEDULING
3177 // set up select call
3178 for (count = 0; count < boundPortCount; count++)
3180 FD_SET (openSockfd[count], &selectFds);
3183 tv.tv_usec = 30000L;
3184 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3186 /* select is reporting a waiting socket. Poll them all to find out which */
3187 if (selectResult > 0)
3189 for (count = 0; count < boundPortCount; count++)
3191 if (FD_ISSET (openSockfd[count], &selectFds))
3195 ts.tv_nsec = 30000L;
3196 i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3197 if (i > 0) for (j = 0; j < i; j++)
3199 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke.ident);
3200 // this isnt as efficient as it could be, we could create a reference table
3201 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3202 // number of listening ports on the average ircd is a small number (less than 20)
3203 // compared to the number of clients (possibly over 2000)
3204 for (count = 0; count < boundPortCount; count++)
3206 if (ke_list[j].ident == openSockfd[count])
3209 char target[MAXBUF], resolved[MAXBUF];
3210 length = sizeof (client);
3211 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3213 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3214 strlcpy (resolved, target, MAXBUF);
3216 if (incomingSockfd < 0)
3218 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3219 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3224 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3226 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3227 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3235 #ifdef _POSIX_PRIORITY_SCHEDULING
3241 close (incomingSockfd);