1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
21 #include "inspircd_config.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
32 #include <sys/types.h>
33 #include <sys/event.h>
38 #include <sys/epoll.h>
45 #include <ext/hash_map>
67 #include "inspstring.h"
69 #include "helperfuncs.h"
71 #include "socketengine.h"
75 int LogLevel = DEFAULT;
76 char ServerName[MAXBUF];
78 char ServerDesc[MAXBUF];
79 char AdminName[MAXBUF];
80 char AdminEmail[MAXBUF];
81 char AdminNick[MAXBUF];
83 char restartpass[MAXBUF];
87 char PrefixQuit[MAXBUF];
88 char DieValue[MAXBUF];
89 char DNSServer[MAXBUF];
91 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
92 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
94 time_t startup_time = time(NULL);
95 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
96 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
97 unsigned int SoftLimit = MAXCLIENTS;
98 extern int MaxWhoResults;
102 char DisabledCommands[MAXBUF];
104 bool AllowHalfop = true;
105 bool AllowProtect = true;
106 bool AllowFounder = true;
108 extern std::vector<Module*> modules;
109 std::vector<std::string> module_names;
110 extern std::vector<ircd_module*> factory;
112 std::vector<InspSocket*> module_sockets;
115 int openSockfd[MAXSOCKS];
117 bool unlimitcore = false;
119 time_t TIME = time(NULL), OLDTIME = time(NULL);
129 bool has_been_netsplit = false;
130 extern std::vector<std::string> include_stack;
132 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
133 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
134 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
135 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
136 typedef std::deque<command_t> command_table;
137 typedef std::map<std::string,time_t> autoconnects;
138 typedef std::vector<std::string> servernamelist;
140 // This table references users by file descriptor.
141 // its an array to make it VERY fast, as all lookups are referenced
142 // by an integer, meaning there is no need for a scan/search operation.
143 userrec* fd_ref_table[65536];
145 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
151 user_hash clientlist;
154 command_table cmdlist;
155 autoconnects autoconns;
161 servernamelist servernames;
163 struct linger linger = { 0 };
164 char MyExecutable[1024];
165 int boundPortCount = 0;
166 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
168 char ModPath[MAXBUF];
172 int has_channel(userrec *u, chanrec *c);
173 int usercount(chanrec *c);
174 int usercount_i(chanrec *c);
175 char* Passwd(userrec *user);
176 bool IsDenied(userrec *user);
177 void AddWhoWas(userrec* u);
179 std::stringstream config_f(stringstream::in | stringstream::out);
181 std::vector<userrec*> all_opers;
185 void AddOper(userrec* user)
187 log(DEBUG,"Oper added to optimization list");
188 all_opers.push_back(user);
191 void AddServerName(std::string servername)
193 log(DEBUG,"Adding server name: %s",servername.c_str());
194 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
196 if (*a == servername)
199 servernames.push_back(servername);
202 const char* FindServerNamePtr(std::string servername)
204 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
206 if (*a == servername)
209 AddServerName(servername);
210 return FindServerNamePtr(servername);
213 void DeleteOper(userrec* user)
215 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
219 log(DEBUG,"Oper removed from optimization list");
226 std::string GetRevision()
228 char Revision[] = "$Revision$";
231 char *v2 = strtok_r(s1," ",&savept);
233 v2 = strtok_r(s1," ",&savept);
235 return std::string(v2);
239 std::string getservername()
244 std::string getserverdesc()
249 std::string getnetworkname()
254 std::string getadminname()
259 std::string getadminemail()
264 std::string getadminnick()
269 void ReadConfig(bool bail, userrec* user)
271 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
272 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
274 std::stringstream errstr;
275 include_stack.clear();
277 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
280 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
283 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
291 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
292 while (!errstr.eof())
294 errstr.getline(dataline,1024);
295 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
300 WriteOpers("There were errors in the configuration file:");
301 while (!errstr.eof())
303 errstr.getline(dataline,1024);
304 WriteOpers(dataline);
311 ConfValue("server","name",0,ServerName,&config_f);
312 ConfValue("server","description",0,ServerDesc,&config_f);
313 ConfValue("server","network",0,Network,&config_f);
314 ConfValue("admin","name",0,AdminName,&config_f);
315 ConfValue("admin","email",0,AdminEmail,&config_f);
316 ConfValue("admin","nick",0,AdminNick,&config_f);
317 ConfValue("files","motd",0,motd,&config_f);
318 ConfValue("files","rules",0,rules,&config_f);
319 ConfValue("power","diepass",0,diepass,&config_f);
320 ConfValue("power","pause",0,pauseval,&config_f);
321 ConfValue("power","restartpass",0,restartpass,&config_f);
322 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
323 ConfValue("die","value",0,DieValue,&config_f);
324 ConfValue("options","loglevel",0,dbg,&config_f);
325 ConfValue("options","netbuffersize",0,NB,&config_f);
326 ConfValue("options","maxwho",0,MW,&config_f);
327 ConfValue("options","allowhalfop",0,AH,&config_f);
328 ConfValue("options","allowprotect",0,AP,&config_f);
329 ConfValue("options","allowfounder",0,AF,&config_f);
330 ConfValue("dns","server",0,DNSServer,&config_f);
331 ConfValue("dns","timeout",0,DNT,&config_f);
332 ConfValue("options","moduledir",0,ModPath,&config_f);
333 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
334 ConfValue("options","somaxconn",0,MCON,&config_f);
335 ConfValue("options","softlimit",0,SLIMT,&config_f);
337 SoftLimit = atoi(SLIMT);
338 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
340 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
341 SoftLimit = MAXCLIENTS;
343 MaxConn = atoi(MCON);
344 if (MaxConn > SOMAXCONN)
345 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
346 NetBufferSize = atoi(NB);
347 MaxWhoResults = atoi(MW);
348 dns_timeout = atoi(DNT);
354 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
356 strlcpy(ModPath,MOD_PATH,MAXBUF);
357 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
358 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
359 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
360 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
362 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
363 NetBufferSize = 10240;
365 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
367 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
370 if (!strcmp(dbg,"debug"))
372 if (!strcmp(dbg,"verbose"))
374 if (!strcmp(dbg,"default"))
376 if (!strcmp(dbg,"sparse"))
378 if (!strcmp(dbg,"none"))
381 log(DEFAULT,"Reading message of the day...");
382 readfile(RULES,rules);
383 log(DEFAULT,"Reading connect classes...");
385 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
388 ConfValue("connect","allow",i,Value,&config_f);
389 ConfValue("connect","timeout",i,timeout,&config_f);
390 ConfValue("connect","flood",i,flood,&config_f);
391 ConfValue("connect","pingfreq",i,pfreq,&config_f);
392 ConfValue("connect","threshold",i,thold,&config_f);
393 ConfValue("connect","sendq",i,sqmax,&config_f);
394 ConfValue("connect","recvq",i,rqmax,&config_f);
397 strlcpy(c.host,Value,MAXBUF);
399 strlcpy(Value,"",MAXBUF);
400 ConfValue("connect","password",i,Value,&config_f);
401 strlcpy(c.pass,Value,MAXBUF);
402 c.registration_timeout = 90; // default is 2 minutes
404 c.flood = atoi(flood);
406 c.sendqmax = 262144; // 256k
407 c.recvqmax = 4096; // 4k
410 c.threshold = atoi(thold);
414 c.sendqmax = atoi(sqmax);
418 c.recvqmax = atoi(rqmax);
422 c.registration_timeout = atoi(timeout);
426 c.pingtime = atoi(pfreq);
428 Classes.push_back(c);
429 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);
433 ConfValue("connect","deny",i,Value,&config_f);
434 strlcpy(c.host,Value,MAXBUF);
436 Classes.push_back(c);
437 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
441 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
442 read_xline_defaults();
443 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
447 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
449 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
450 ConfValue("link","name",i,Link_ServerName,&config_f);
451 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
452 if (strcmp(Link_AConn,""))
454 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
459 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
462 log(DEFAULT,"Adding and removing modules due to rehash...");
464 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
466 // store the old module names
467 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
469 old_module_names.push_back(*t);
472 // get the new module names
473 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
475 ConfValue("module","name",count2,Value,&config_f);
476 new_module_names.push_back(Value);
479 // now create a list of new modules that are due to be loaded
480 // and a seperate list of modules which are due to be unloaded
481 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
484 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
490 added_modules.push_back(*_new);
492 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
495 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
501 removed_modules.push_back(*oldm);
503 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
505 int rem = 0, add = 0;
506 if (!removed_modules.empty())
507 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
509 if (UnloadModule(removing->c_str()))
511 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
512 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
517 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
520 if (!added_modules.empty())
521 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
523 if (LoadModule(adding->c_str()))
525 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
526 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
531 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
534 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());
539 /* add a channel to a user, creating the record for it if needed and linking
540 * it to the user record */
542 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
544 if ((!user) || (!cn))
546 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
554 strncpy(cname,cn,MAXBUF);
556 // we MUST declare this wherever we use FOREACH_RESULT
559 if (strlen(cname) > CHANMAX)
561 cname[CHANMAX] = '\0';
564 log(DEBUG,"add_channel: %s %s",user->nick,cname);
566 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
568 return NULL; // already on the channel!
572 if (!FindChan(cname))
574 if (strcmp(ServerName,u->server))
577 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
578 if (MOD_RESULT == 1) {
583 /* create a new one */
584 log(DEBUG,"add_channel: creating: %s",cname);
586 chanlist[cname] = new chanrec();
588 strlcpy(chanlist[cname]->name, cname,CHANMAX);
589 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
590 chanlist[cname]->created = TIME;
591 strcpy(chanlist[cname]->topic, "");
592 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
593 chanlist[cname]->topicset = 0;
594 Ptr = chanlist[cname];
595 log(DEBUG,"add_channel: created: %s",cname);
596 /* set created to 2 to indicate user
597 * is the first in the channel
598 * and should be given ops */
604 /* channel exists, just fish out a pointer to its struct */
605 Ptr = FindChan(cname);
608 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
610 // remote users are allowed us to bypass channel modes
611 // and bans (used by servers)
612 if (!strcasecmp(ServerName,user->server))
614 log(DEBUG,"Not overriding...");
616 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
617 if (MOD_RESULT == 1) {
620 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
624 log(DEBUG,"add_channel: checking key, invite, etc");
626 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
631 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
634 log(DEBUG,"add_channel: no key given in JOIN");
635 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
640 if (strcasecmp(key,Ptr->key))
642 log(DEBUG,"add_channel: bad key given in JOIN");
643 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
648 log(DEBUG,"add_channel: no key");
651 FOREACH_RESULT(OnCheckInvite(user, Ptr));
654 if (Ptr->binarymodes & CM_INVITEONLY)
656 log(DEBUG,"add_channel: channel is +i");
657 if (user->IsInvited(Ptr->name))
659 /* user was invited to channel */
660 /* there may be an optional channel NOTICE here */
664 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
668 log(DEBUG,"add_channel: channel is not +i");
671 FOREACH_RESULT(OnCheckLimit(user, Ptr));
676 if (usercount(Ptr) >= Ptr->limit)
678 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
683 log(DEBUG,"add_channel: about to walk banlist");
685 FOREACH_RESULT(OnCheckBan(user, Ptr));
688 /* check user against the channel banlist */
691 if (Ptr->bans.size())
693 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
695 if (match(user->GetFullHost(),i->data))
697 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
703 log(DEBUG,"add_channel: bans checked");
711 user->RemoveInvite(Ptr->name);
714 log(DEBUG,"add_channel: invites removed");
719 log(DEBUG,"Overridden checks");
727 log(DEBUG,"Passed channel checks");
729 for (int index =0; index != MAXCHANS; index++)
731 log(DEBUG,"Check location %d",index);
732 if (user->chans[index].channel == NULL)
734 log(DEBUG,"Adding into their channel list at location %d",index);
738 /* first user in is given ops */
739 user->chans[index].uc_modes = UCMODE_OP;
743 user->chans[index].uc_modes = 0;
745 user->chans[index].channel = Ptr;
746 Ptr->AddUser((char*)user);
747 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
749 log(DEBUG,"Sent JOIN to client");
753 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
754 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
757 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
758 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
759 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
760 FOREACH_MOD OnUserJoin(user,Ptr);
764 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
765 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
769 /* remove a channel from a users record, and remove the record from memory
770 * if the channel has become empty */
772 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
774 if ((!user) || (!cname))
776 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
782 if ((!cname) || (!user))
787 Ptr = FindChan(cname);
794 FOREACH_MOD OnUserPart(user,Ptr);
795 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
797 for (int i =0; i != MAXCHANS; i++)
799 /* zap it from the channel list of the user */
800 if (user->chans[i].channel == Ptr)
804 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
808 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
810 user->chans[i].uc_modes = 0;
811 user->chans[i].channel = NULL;
812 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
817 Ptr->DelUser((char*)user);
819 /* if there are no users left on the channel */
822 chan_hash::iterator iter = chanlist.find(Ptr->name);
824 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
826 /* kill the record */
827 if (iter != chanlist.end())
829 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
831 chanlist.erase(iter);
839 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
841 if ((!src) || (!user) || (!Ptr) || (!reason))
843 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
847 if ((!Ptr) || (!user) || (!src))
852 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
854 if (!has_channel(user,Ptr))
856 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
861 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
862 if (MOD_RESULT == ACR_DENY)
865 if (MOD_RESULT == ACR_DEFAULT)
867 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
869 if (cstatus(src,Ptr) == STATUS_HOP)
871 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
875 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
883 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
887 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
889 for (int i =0; i != MAXCHANS; i++)
891 /* zap it from the channel list of the user */
892 if (user->chans[i].channel)
893 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
895 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
896 user->chans[i].uc_modes = 0;
897 user->chans[i].channel = NULL;
898 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
903 Ptr->DelUser((char*)user);
905 /* if there are no users left on the channel */
908 chan_hash::iterator iter = chanlist.find(Ptr->name);
910 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
912 /* kill the record */
913 if (iter != chanlist.end())
915 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
917 chanlist.erase(iter);
925 /* This function pokes and hacks at a parameter list like the following:
927 * PART #winbot,#darkgalaxy :m00!
929 * to turn it into a series of individual calls like this:
932 * PART #darkgalaxy :m00!
934 * The seperate calls are sent to a callback function provided by the caller
935 * (the caller will usually call itself recursively). The callback function
936 * must be a command handler. Calling this function on a line with no list causes
937 * no action to be taken. You must provide a starting and ending parameter number
938 * where the range of the list can be found, useful if you have a terminating
939 * parameter as above which is actually not part of the list, or parameters
940 * before the actual list as well. This code is used by many functions which
941 * can function as "one to list" (see the RFC) */
943 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
948 char blog[32][MAXBUF];
949 char blog2[32][MAXBUF];
950 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
954 for (int i = 0; i <32; i++)
957 for (int i = 0; i <32; i++)
961 for (int i = 0; i <10; i++)
970 if (pcnt > 1) /* we have a key to copy */
972 strlcpy(keystr,parameters[1],MAXBUF);
976 if (!parameters[start])
980 if (!strchr(parameters[start],','))
985 for (int i = start; i <= end; i++)
989 strlcat(plist,parameters[i],MAXBUF);
997 for (int i = 0; i < t; i++)
1002 strlcpy(blog[j++],param,MAXBUF);
1006 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1011 strlcpy(blog[j++],param,MAXBUF);
1014 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1019 if ((joins) && (keystr))
1021 if (strchr(keystr,','))
1025 t2 = strlen(keystr);
1026 for (int i = 0; i < t2; i++)
1028 if (keystr[i] == ',')
1031 strlcpy(blog2[j++],param,MAXBUF);
1035 strlcpy(blog2[j++],param,MAXBUF);
1040 for (j = 0; j < total; j++)
1046 for (q = end; q < pcnt-1; q++)
1048 if (parameters[q+1])
1050 pars[q-end+1] = parameters[q+1];
1053 if ((joins) && (parameters[1]))
1064 /* repeatedly call the function with the hacked parameter list */
1065 if ((joins) && (pcnt > 1))
1069 // pars[1] already set up and containing key from blog2[j]
1074 pars[1] = parameters[1];
1080 fn(pars,pcnt-(end-start),u);
1089 void kill_link(userrec *user,const char* r)
1091 user_hash::iterator iter = clientlist.find(user->nick);
1093 char reason[MAXBUF];
1095 strncpy(reason,r,MAXBUF);
1097 if (strlen(reason)>MAXQUIT)
1099 reason[MAXQUIT-1] = '\0';
1102 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1103 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1104 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1106 if (user->registered == 7) {
1107 FOREACH_MOD OnUserQuit(user,reason);
1108 WriteCommonExcept(user,"QUIT :%s",reason);
1111 user->FlushWriteBuf();
1113 FOREACH_MOD OnUserDisconnect(user);
1117 FOREACH_MOD OnRawSocketClose(user->fd);
1119 user->CloseSocket();
1122 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1123 // if they were an oper with +s.
1124 if (user->registered == 7) {
1125 purge_empty_chans(user);
1126 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1127 if (!strcmp(user->server,ServerName))
1128 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1132 if (iter != clientlist.end())
1134 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1136 fd_ref_table[user->fd] = NULL;
1137 clientlist.erase(iter);
1142 void kill_link_silent(userrec *user,const char* r)
1144 user_hash::iterator iter = clientlist.find(user->nick);
1146 char reason[MAXBUF];
1148 strncpy(reason,r,MAXBUF);
1150 if (strlen(reason)>MAXQUIT)
1152 reason[MAXQUIT-1] = '\0';
1155 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1156 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1157 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1159 user->FlushWriteBuf();
1161 if (user->registered == 7) {
1162 FOREACH_MOD OnUserQuit(user,reason);
1163 WriteCommonExcept(user,"QUIT :%s",reason);
1166 FOREACH_MOD OnUserDisconnect(user);
1170 FOREACH_MOD OnRawSocketClose(user->fd);
1172 user->CloseSocket();
1175 if (user->registered == 7) {
1176 purge_empty_chans(user);
1179 if (iter != clientlist.end())
1181 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1183 fd_ref_table[user->fd] = NULL;
1184 clientlist.erase(iter);
1190 /*void *task(void *arg)
1193 cout << (char *)arg;
1199 int main(int argc, char** argv)
1203 log(DEBUG,"*** InspIRCd starting up!");
1204 if (!FileExists(CONFIG_FILE))
1206 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1207 log(DEFAULT,"main: no config");
1208 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1212 for (int i = 1; i < argc; i++)
1214 if (!strcmp(argv[i],"-nofork")) {
1217 if (!strcmp(argv[i],"-wait")) {
1220 if (!strcmp(argv[i],"-nolimit")) {
1226 strlcpy(MyExecutable,argv[0],MAXBUF);
1228 // initialize the lowercase mapping table
1229 for (unsigned int cn = 0; cn < 256; cn++)
1231 // lowercase the uppercase chars
1232 for (unsigned int cn = 65; cn < 91; cn++)
1233 lowermap[cn] = tolower(cn);
1234 // now replace the specific chars for scandanavian comparison
1235 lowermap[(unsigned)'['] = '{';
1236 lowermap[(unsigned)']'] = '}';
1237 lowermap[(unsigned)'\\'] = '|';
1239 if (InspIRCd(argv,argc) == ERROR)
1241 log(DEFAULT,"main: daemon function bailed");
1242 printf("ERROR: could not initialise. Shutting down.\n");
1249 template<typename T> inline string ConvToStr(const T &in)
1252 if (!(tmp << in)) return string();
1256 /* re-allocates a nick in the user_hash after they change nicknames,
1257 * returns a pointer to the new user as it may have moved */
1259 userrec* ReHashNick(char* Old, char* New)
1261 //user_hash::iterator newnick;
1262 user_hash::iterator oldnick = clientlist.find(Old);
1264 log(DEBUG,"ReHashNick: %s %s",Old,New);
1266 if (!strcasecmp(Old,New))
1268 log(DEBUG,"old nick is new nick, skipping");
1269 return oldnick->second;
1272 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1274 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1276 userrec* olduser = oldnick->second;
1277 clientlist[New] = olduser;
1278 clientlist.erase(oldnick);
1280 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1282 return clientlist[New];
1285 /* adds or updates an entry in the whowas list */
1286 void AddWhoWas(userrec* u)
1288 whowas_hash::iterator iter = whowas.find(u->nick);
1289 WhoWasUser *a = new WhoWasUser();
1290 strlcpy(a->nick,u->nick,NICKMAX);
1291 strlcpy(a->ident,u->ident,IDENTMAX);
1292 strlcpy(a->dhost,u->dhost,160);
1293 strlcpy(a->host,u->host,160);
1294 strlcpy(a->fullname,u->fullname,MAXGECOS);
1295 strlcpy(a->server,u->server,256);
1296 a->signon = u->signon;
1298 /* MAX_WHOWAS: max number of /WHOWAS items
1299 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1300 * can be replaced by a newer one
1303 if (iter == whowas.end())
1305 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1307 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1309 // 3600 seconds in an hour ;)
1310 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1312 // delete the old one
1313 if (i->second) delete i->second;
1314 // replace with new one
1316 log(DEBUG,"added WHOWAS entry, purged an old record");
1320 // no space left and user doesnt exist. Don't leave ram in use!
1321 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1326 log(DEBUG,"added fresh WHOWAS entry");
1327 whowas[a->nick] = a;
1332 log(DEBUG,"updated WHOWAS entry");
1333 if (iter->second) delete iter->second;
1339 void* dns_task(void* arg)
1341 userrec* u = (userrec*)arg;
1342 log(DEBUG,"DNS thread for user %s",u->nick);
1347 if (dns1.ReverseLookup(u->ip))
1349 log(DEBUG,"DNS Step 1");
1350 while (!dns1.HasResult())
1354 host = dns1.GetResult();
1357 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1358 if (dns2.ForwardLookup(host))
1360 while (!dns2.HasResult())
1364 ip = dns2.GetResultIP();
1365 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1366 if (ip == std::string(u->ip))
1368 log(DEBUG,"DNS Step 4");
1369 if (host.length() < 160)
1371 log(DEBUG,"DNS Step 5");
1372 strcpy(u->host,host.c_str());
1373 strcpy(u->dhost,host.c_str());
1384 /* add a client connection to the sockets list */
1385 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1389 user_hash::iterator iter;
1391 tempnick = ConvToStr(socket) + "-unknown";
1392 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1394 iter = clientlist.find(tempnick);
1397 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1398 // using one as a registered connection. As theyre per fd, we can also safely assume
1399 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1400 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1401 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1402 // issue in earlier alphas/betas
1403 if (iter != clientlist.end())
1405 userrec* goner = iter->second;
1407 clientlist.erase(iter);
1411 * It is OK to access the value here this way since we know
1412 * it exists, we just created it above.
1414 * At NO other time should you access a value in a map or a
1415 * hash_map this way.
1417 clientlist[tempnick] = new userrec();
1419 NonBlocking(socket);
1420 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1422 clientlist[tempnick]->fd = socket;
1423 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1424 strlcpy(clientlist[tempnick]->host, host,160);
1425 strlcpy(clientlist[tempnick]->dhost, host,160);
1426 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1427 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1428 clientlist[tempnick]->registered = 0;
1429 clientlist[tempnick]->signon = TIME+dns_timeout;
1430 clientlist[tempnick]->lastping = 1;
1431 clientlist[tempnick]->port = port;
1432 strlcpy(clientlist[tempnick]->ip,ip,16);
1434 // set the registration timeout for this user
1435 unsigned long class_regtimeout = 90;
1436 int class_flood = 0;
1437 long class_threshold = 5;
1438 long class_sqmax = 262144; // 256kb
1439 long class_rqmax = 4096; // 4k
1441 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1443 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1445 class_regtimeout = (unsigned long)i->registration_timeout;
1446 class_flood = i->flood;
1447 clientlist[tempnick]->pingmax = i->pingtime;
1448 class_threshold = i->threshold;
1449 class_sqmax = i->sendqmax;
1450 class_rqmax = i->recvqmax;
1455 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1456 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1457 clientlist[tempnick]->flood = class_flood;
1458 clientlist[tempnick]->threshold = class_threshold;
1459 clientlist[tempnick]->sendqmax = class_sqmax;
1460 clientlist[tempnick]->recvqmax = class_rqmax;
1462 for (int i = 0; i < MAXCHANS; i++)
1464 clientlist[tempnick]->chans[i].channel = NULL;
1465 clientlist[tempnick]->chans[i].uc_modes = 0;
1468 if (clientlist.size() > SoftLimit)
1470 kill_link(clientlist[tempnick],"No more connections allowed");
1474 if (clientlist.size() >= MAXCLIENTS)
1476 kill_link(clientlist[tempnick],"No more connections allowed");
1480 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1481 // its a pretty big but for the moment valid assumption:
1482 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1483 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1484 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1485 // which for the time being is a physical impossibility (even the largest networks dont have more
1486 // than about 10,000 users on ONE server!)
1487 if ((unsigned)socket > 65534)
1489 kill_link(clientlist[tempnick],"Server is full");
1494 char* e = matches_exception(ip);
1497 char* r = matches_zline(ip);
1500 char reason[MAXBUF];
1501 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1502 kill_link(clientlist[tempnick],reason);
1506 fd_ref_table[socket] = clientlist[tempnick];
1509 // initialize their dns lookup thread
1510 //if (pthread_create(&clientlist[tempnick]->dnsthread, NULL, dns_task, (void *)clientlist[tempnick]) != 0)
1512 // log(DEBUG,"Failed to create DNS lookup thread for user %s",clientlist[tempnick]->nick);
1516 /* shows the message of the day, and any other on-logon stuff */
1517 void FullConnectUser(userrec* user)
1520 user->idle_lastmsg = TIME;
1521 log(DEBUG,"ConnectUser: %s",user->nick);
1523 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1525 kill_link(user,"Invalid password");
1530 kill_link(user,"Unauthorised connection");
1534 char match_against[MAXBUF];
1535 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1536 char* e = matches_exception(match_against);
1539 char* r = matches_gline(match_against);
1542 char reason[MAXBUF];
1543 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1544 kill_link_silent(user,reason);
1547 r = matches_kline(user->host);
1550 char reason[MAXBUF];
1551 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1552 kill_link_silent(user,reason);
1557 // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1558 user->registered = 7;
1560 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1561 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1562 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1563 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1564 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1565 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1566 std::stringstream v;
1567 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1568 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1569 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1571 std::string data005 = v.str();
1572 FOREACH_MOD On005Numeric(data005);
1573 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1574 // so i'd better split it :)
1575 std::stringstream out(data005);
1576 std::string token = "";
1577 std::string line5 = "";
1578 int token_counter = 0;
1582 line5 = line5 + token + " ";
1584 if ((token_counter >= 13) || (out.eof() == true))
1586 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1593 // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1594 FOREACH_MOD OnUserConnect(user);
1595 FOREACH_MOD OnGlobalConnect(user);
1596 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1600 /* shows the message of the day, and any other on-logon stuff */
1601 void ConnectUser(userrec *user)
1603 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1604 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1606 FullConnectUser(user);
1610 std::string GetVersionString()
1612 char Revision[] = "$Revision$";
1613 char versiondata[MAXBUF];
1614 char *s1 = Revision;
1616 char *v2 = strtok_r(s1," ",&savept);
1618 v2 = strtok_r(s1," ",&savept);
1620 char socketengine[] = engine_name;
1622 char dnsengine[] = "multithread";
1624 char dnsengine[] = "singlethread";
1626 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine,dnsengine);
1630 void handle_version(char **parameters, int pcnt, userrec *user)
1632 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1636 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1638 for (unsigned int i = 0; i < cmdlist.size(); i++)
1640 if (!strcasecmp(cmdlist[i].command,commandname))
1642 if (cmdlist[i].handler_function)
1644 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1646 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1648 if (cmdlist[i].flags_needed)
1650 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1668 // calls a handler function for a command
1670 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1672 for (unsigned int i = 0; i < cmdlist.size(); i++)
1674 if (!strcasecmp(cmdlist[i].command,commandname))
1676 if (cmdlist[i].handler_function)
1678 if (pcnt>=cmdlist[i].min_params)
1680 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1682 if (cmdlist[i].flags_needed)
1684 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1686 cmdlist[i].handler_function(parameters,pcnt,user);
1691 cmdlist[i].handler_function(parameters,pcnt,user);
1701 void force_nickchange(userrec* user,const char* newnick)
1708 FOREACH_RESULT(OnUserPreNick(user,newnick));
1711 kill_link(user,"Nickname collision");
1714 if (matches_qline(newnick))
1717 kill_link(user,"Nickname collision");
1725 strncpy(nick,newnick,MAXBUF);
1727 if (user->registered == 7)
1731 handle_nick(pars,1,user);
1737 int process_parameters(char **command_p,char *parameters)
1740 int q = strlen(parameters);
1743 /* no parameters, command_p invalid! */
1746 if (parameters[0] == ':')
1748 command_p[0] = parameters+1;
1753 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1755 /* only one parameter */
1756 command_p[0] = parameters;
1757 if (parameters[0] == ':')
1759 if (strchr(parameters,' ') != NULL)
1767 command_p[j++] = parameters;
1768 for (int i = 0; i <= q; i++)
1770 if (parameters[i] == ' ')
1772 command_p[j++] = parameters+i+1;
1773 parameters[i] = '\0';
1774 if (command_p[j-1][0] == ':')
1776 *command_p[j-1]++; /* remove dodgy ":" */
1778 /* parameter like this marks end of the sequence */
1782 return j; /* returns total number of items in the list */
1785 void process_command(userrec *user, char* cmd)
1789 char *command_p[127];
1790 char p[MAXBUF], temp[MAXBUF];
1791 int j, items, cmd_found;
1793 for (int i = 0; i < 127; i++)
1794 command_p[i] = NULL;
1809 int total_params = 0;
1812 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1814 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1817 // found a 'trailing', we dont count them after this.
1825 // another phidjit bug...
1826 if (total_params > 126)
1828 *(strchr(cmd,' ')) = '\0';
1829 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1833 strlcpy(temp,cmd,MAXBUF);
1835 std::string tmp = cmd;
1836 for (int i = 0; i <= MODCOUNT; i++)
1838 std::string oldtmp = tmp;
1839 modules[i]->OnServerRaw(tmp,true,user);
1842 log(DEBUG,"A Module changed the input string!");
1843 log(DEBUG,"New string: %s",tmp.c_str());
1844 log(DEBUG,"Old string: %s",oldtmp.c_str());
1848 strlcpy(cmd,tmp.c_str(),MAXBUF);
1849 strlcpy(temp,cmd,MAXBUF);
1851 if (!strchr(cmd,' '))
1853 /* no parameters, lets skip the formalities and not chop up
1855 log(DEBUG,"About to preprocess command with no params");
1857 command_p[0] = NULL;
1859 for (unsigned int i = 0; i <= strlen(cmd); i++)
1861 cmd[i] = toupper(cmd[i]);
1869 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1870 for (unsigned int i = 0; i < strlen(temp); i++)
1872 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1878 /* split the full string into a command plus parameters */
1882 if (strchr(cmd,' '))
1884 for (unsigned int i = 0; i <= strlen(cmd); i++)
1886 /* capitalise the command ONLY, leave params intact */
1887 cmd[i] = toupper(cmd[i]);
1888 /* are we nearly there yet?! :P */
1892 parameters = cmd+i+1;
1900 for (unsigned int i = 0; i <= strlen(cmd); i++)
1902 cmd[i] = toupper(cmd[i]);
1909 if (strlen(command)>MAXCOMMAND)
1911 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1915 for (unsigned int x = 0; x < strlen(command); x++)
1917 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1919 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1921 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1924 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1931 for (unsigned int i = 0; i != cmdlist.size(); i++)
1933 if (cmdlist[i].command[0])
1935 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1941 items = process_parameters(command_p,parameters);
1946 command_p[0] = NULL;
1952 command_p[0] = NULL;
1957 /* activity resets the ping pending timer */
1958 user->nping = TIME + user->pingmax;
1959 if ((items) < cmdlist[i].min_params)
1961 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1962 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1965 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1967 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1968 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1972 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1974 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1975 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1979 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1981 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1983 if ((!isnick(user->nick)) || (user->registered != 7))
1985 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1986 WriteServ(user->fd,"451 %s :You have not registered",command);
1990 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1992 std::stringstream dcmds(DisabledCommands);
1993 while (!dcmds.eof())
1995 std::string thiscmd;
1997 if (!strcasecmp(thiscmd.c_str(),command))
1999 // command is disabled!
2000 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2005 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2007 if (cmdlist[i].handler_function)
2010 /* ikky /stats counters */
2013 cmdlist[i].use_count++;
2014 cmdlist[i].total_bytes+=strlen(temp);
2018 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2019 if (MOD_RESULT == 1) {
2023 /* WARNING: nothing may come after the
2024 * command handler call, as the handler
2025 * may free the user structure! */
2027 cmdlist[i].handler_function(command_p,items,user);
2033 WriteServ(user->fd,"451 %s :You have not registered",command);
2041 if ((!cmd_found) && (user))
2044 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2048 bool removecommands(const char* source)
2050 bool go_again = true;
2054 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2056 if (!strcmp(i->source,source))
2058 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2069 void process_buffer(const char* cmdbuf,userrec *user)
2073 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2079 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2086 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2088 strlcpy(cmd,cmdbuf,MAXBUF);
2093 int sl = strlen(cmd)-1;
2094 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2099 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2104 while (cmd[sl] == ' ') // strip trailing spaces
2114 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2116 if ((user) && (cmd))
2118 process_command(user,cmd);
2122 char MODERR[MAXBUF];
2129 void erase_factory(int j)
2132 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2137 factory.push_back(NULL);
2144 void erase_module(int j)
2147 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2153 modules.push_back(NULL);
2159 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2163 module_names.erase(v);
2171 bool UnloadModule(const char* filename)
2173 std::string filename_str = filename;
2174 for (unsigned int j = 0; j != module_names.size(); j++)
2176 if (module_names[j] == filename_str)
2178 if (modules[j]->GetVersion().Flags & VF_STATIC)
2180 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2181 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2184 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2186 log(DEBUG,"Deleting module...");
2188 log(DEBUG,"Erasing module entry...");
2190 log(DEBUG,"Removing dependent commands...");
2191 removecommands(filename);
2192 log(DEFAULT,"Module %s unloaded",filename);
2197 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2198 snprintf(MODERR,MAXBUF,"Module not loaded");
2202 bool LoadModule(const char* filename)
2204 char modfile[MAXBUF];
2206 snprintf(modfile,MAXBUF,"%s",filename);
2208 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2210 std::string filename_str = filename;
2212 if (!DirValid(modfile))
2214 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2215 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2219 log(DEBUG,"Loading module: %s",modfile);
2221 if (FileExists(modfile))
2224 for (unsigned int j = 0; j < module_names.size(); j++)
2226 if (module_names[j] == filename_str)
2228 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2229 snprintf(MODERR,MAXBUF,"Module already loaded");
2233 ircd_module* a = new ircd_module(modfile);
2234 factory[MODCOUNT+1] = a;
2235 if (factory[MODCOUNT+1]->LastError())
2237 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2238 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2242 if (factory[MODCOUNT+1]->factory)
2244 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2245 modules[MODCOUNT+1] = m;
2246 /* save the module and the module's classfactory, if
2247 * this isnt done, random crashes can occur :/ */
2248 module_names.push_back(filename);
2252 log(DEFAULT,"Unable to load %s",modfile);
2253 snprintf(MODERR,MAXBUF,"Factory function failed!");
2260 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2261 snprintf(MODERR,MAXBUF,"Module file could not be found");
2266 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2271 int InspIRCd(char** argv, int argc)
2273 struct sockaddr_in client,server;
2274 char addrs[MAXBUF][255];
2275 int incomingSockfd, result = TRUE;
2279 int selectResult = 0, selectResult2 = 0;
2282 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2285 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2286 log_file = fopen(logpath.c_str(),"a+");
2289 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2294 printf("Logging to ircd.log...\n");
2296 printf("Logging to %s...\n",logpath.c_str());
2299 log(DEFAULT,"$Id$");
2302 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2304 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2306 SetupCommandTable();
2307 log(DEBUG,"InspIRCd: startup: default command table set up");
2309 ReadConfig(true,NULL);
2312 printf("WARNING: %s\n\n",DieValue);
2313 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2316 log(DEBUG,"InspIRCd: startup: read config");
2318 AddServerName(ServerName);
2320 int clientportcount = 0;
2322 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2324 ConfValue("bind","port",count,configToken,&config_f);
2325 ConfValue("bind","address",count,Addr,&config_f);
2326 ConfValue("bind","type",count,Type,&config_f);
2327 if (!strcmp(Type,"servers"))
2329 // modules handle this bind type now.
2333 ports[clientportcount] = atoi(configToken);
2334 strlcpy(addrs[clientportcount],Addr,256);
2337 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2339 portCount = clientportcount;
2341 log(DEBUG,"InspIRCd: startup: read %lu total client ports",(unsigned long)portCount);
2342 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2346 /* BugFix By Craig! :p */
2348 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2350 ConfValue("module","name",count,configToken,&config_f);
2351 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2352 if (!LoadModule(configToken))
2354 log(DEFAULT,"Exiting due to a module loader error.");
2355 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2359 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2361 startup_time = time(NULL);
2364 ConfValue("pid","file",0,PID,&config_f);
2365 // write once here, to try it out and make sure its ok
2368 /* setup select call */
2370 FD_ZERO(&selectFds);
2372 log(DEBUG,"InspIRCd: startup: zero selects");
2373 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2375 for (count = 0; count < portCount; count++)
2377 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2379 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2382 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2384 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2386 else /* well we at least bound to one socket so we'll continue */
2392 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2394 /* if we didn't bind to anything then abort */
2395 if (boundPortCount == 0)
2397 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2398 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2403 printf("\nInspIRCd is now running!\n");
2407 log(VERBOSE,"Not forking as -nofork was specified");
2411 if (DaemonSeed() == ERROR)
2413 log(DEFAULT,"InspIRCd: startup: can't daemonise");
2414 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2424 length = sizeof (client);
2427 tvs.tv_usec = 10000L;
2430 tv.tv_usec = 10000L;
2433 tval.tv_usec = 10000L;
2435 int total_in_this_set = 0;
2436 int i = 0, v = 0, j = 0, cycle_iter = 0;
2437 bool expire_run = false;
2439 cycle_iter = i = j = 0; // stop the compiler whining - these may be marked unused in certain socket engine types
2441 /* main loop, this never returns */
2444 #ifdef _POSIX_PRIORITY_SCHEDULING
2450 // we only read time() once per iteration rather than tons of times!
2454 #ifndef THREADED_DNS
2458 unsigned int numsockets = module_sockets.size();
2459 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2461 InspSocket* s = (InspSocket*)*a;
2462 if ((s) && (!s->Poll()))
2464 log(DEBUG,"Socket poll returned false, close and bail");
2466 module_sockets.erase(a);
2470 // we gained a socket, sarper
2471 if (module_sockets.size() != numsockets) break;
2474 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2475 // them in a list, then reap the list every second or so.
2476 if (((TIME % 5) == 0) && (!expire_run))
2479 FOREACH_MOD OnBackgroundTimer(TIME);
2483 if ((TIME % 5) == 1)
2486 // fix by brain - this must be below any manipulation of the hashmap by modules
2487 user_hash::iterator count2 = clientlist.begin();
2490 while (count2 != clientlist.end())
2496 total_in_this_set = 0;
2498 user_hash::iterator xcount = count2;
2499 user_hash::iterator endingiter = count2;
2501 if (count2 == clientlist.end()) break;
2503 userrec* curr = NULL;
2506 curr = count2->second;
2508 if ((long)curr == -1)
2511 if ((curr) && (curr->fd != 0))
2513 #ifdef _POSIX_PRIORITY_SCHEDULING
2516 // assemble up to 64 sockets into an fd_set
2517 // to implement a pooling mechanism.
2519 // This should be up to 64x faster than the
2520 // old implementation.
2522 while (total_in_this_set < 1024)
2524 if (count2 != clientlist.end())
2526 curr = count2->second;
2527 if ((long)curr == -1)
2529 int currfd = curr->fd;
2530 // we don't check the state of remote users.
2531 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2533 curr->FlushWriteBuf();
2534 if (curr->GetWriteError() != "")
2536 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2537 kill_link(curr,curr->GetWriteError().c_str());
2541 FD_SET (curr->fd, &sfd);
2543 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2544 // their connection class.
2545 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2547 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2548 kill_link(curr,"Registration timeout");
2551 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2553 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
2554 curr->dns_done = true;
2556 FullConnectUser(curr);
2557 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2560 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
2562 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2563 FullConnectUser(curr);
2564 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2567 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2569 if ((!curr->lastping) && (curr->registered == 7))
2571 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2572 kill_link(curr,"Ping timeout");
2575 Write(curr->fd,"PING :%s",ServerName);
2576 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2578 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2582 total_in_this_set++;
2586 endingiter = count2;
2587 count2 = xcount; // roll back to where we were
2589 // KQUEUE and EPOLL: We don't go through a loop to fill the fd_set so instead we must manually do this loop every now and again.
2590 // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
2592 if (cycle_iter > 20) while (count2 != clientlist.end())
2595 if (count2 != clientlist.end())
2597 curr = count2->second;
2598 if ((long)curr == -1)
2600 int currfd = curr->fd;
2601 // we don't check the state of remote users.
2602 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2604 curr->FlushWriteBuf();
2605 if (curr->GetWriteError() != "")
2607 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2608 kill_link(curr,curr->GetWriteError().c_str());
2612 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2613 // their connection class.
2614 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2616 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2617 kill_link(curr,"Registration timeout");
2621 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2623 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
2624 curr->dns_done = true;
2626 FullConnectUser(curr);
2627 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2630 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2632 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2633 FullConnectUser(curr);
2634 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2637 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2639 if ((!curr->lastping) && (curr->registered == 7))
2641 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2642 kill_link(curr,"Ping timeout");
2645 Write(curr->fd,"PING :%s",ServerName);
2646 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2648 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2655 // increment the counter right to the end of the list, as kqueue processes everything in one go
2661 #ifdef _POSIX_PRIORITY_SCHEDULING
2667 log(DEBUG,"Data waiting on socket %d",cu->fd);
2670 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
2673 result = cu->ReadData(data, 65535);
2677 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
2680 log(DEBUG,"Read result: %d",result);
2683 statsRecv += result;
2684 // perform a check on the raw buffer as an array (not a string!) to remove
2685 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
2686 // hopefully this should stop even more people whining about "Unknown command: *"
2687 for (int checker = 0; checker < result; checker++)
2689 if ((data[checker] == 0) || (data[checker] == 7))
2690 data[checker] = ' ';
2693 data[result] = '\0';
2694 userrec* current = cu;
2695 int currfd = current->fd;
2697 // add the data to the users buffer
2699 if (!current->AddBuffer(data))
2701 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
2702 if (current->registered == 7)
2704 kill_link(current,"RecvQ exceeded");
2708 WriteOpers("*** Excess flood from %s",current->ip);
2709 log(DEFAULT,"Excess flood from: %s",current->ip);
2710 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2715 if (current->recvq.length() > (unsigned)NetBufferSize)
2717 if (current->registered == 7)
2719 kill_link(current,"RecvQ exceeded");
2723 WriteOpers("*** Excess flood from %s",current->ip);
2724 log(DEFAULT,"Excess flood from: %s",current->ip);
2725 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2730 // while there are complete lines to process...
2731 while (current->BufferIsReady())
2734 if (TIME > current->reset_due)
2736 current->reset_due = TIME + current->threshold;
2737 current->lines_in = 0;
2739 current->lines_in++;
2740 if (current->lines_in > current->flood)
2742 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2743 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2744 kill_link(current,"Excess flood");
2747 if ((floodlines > current->flood) && (current->flood != 0))
2749 if (current->registered == 7)
2751 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2752 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2753 kill_link(current,"Excess flood");
2757 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2762 char sanitized[MAXBUF];
2763 // use GetBuffer to copy single lines into the sanitized string
2764 std::string single_line = current->GetBuffer();
2765 current->bytes_in += single_line.length();
2767 if (single_line.length()>512)
2769 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2770 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2771 kill_link(current,"Excess flood");
2774 strlcpy(sanitized,single_line.c_str(),MAXBUF);
2777 userrec* old_comp = fd_ref_table[currfd];
2778 // we're gonna re-scan to check if the nick is gone, after every
2779 // command - if it has, we're gonna bail
2780 process_buffer(sanitized,current);
2781 // look for the user's record in case it's changed... if theyve quit,
2782 // we cant do anything more with their buffer, so bail.
2783 // there used to be an ugly, slow loop here. Now we have a reference
2784 // table, life is much easier (and FASTER)
2785 userrec* new_comp = fd_ref_table[currfd];
2786 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
2794 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
2796 log(DEBUG,"killing: %s",cu->nick);
2797 kill_link(cu,strerror(errno));
2801 // result EAGAIN means nothing read
2802 if (result == EAGAIN)
2810 else if (result > 0)
2815 for (int q = 0; q < total_in_this_set; q++)
2821 #ifdef _POSIX_PRIORITY_SCHEDULING
2827 char target[MAXBUF], resolved[MAXBUF];
2828 length = sizeof (client);
2829 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2830 log(DEBUG,"Accepted socket %d",incomingSockfd);
2832 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2833 strlcpy (resolved, target, MAXBUF);
2835 if (incomingSockfd < 0)
2837 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
2838 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
2843 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
2845 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
2846 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2853 #ifdef _POSIX_PRIORITY_SCHEDULING
2859 close (incomingSockfd);