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>
33 #include <ext/hash_map>
55 #include "inspstring.h"
57 #include "helperfuncs.h"
59 #include "socketengine.h"
63 int LogLevel = DEFAULT;
64 char ServerName[MAXBUF];
66 char ServerDesc[MAXBUF];
67 char AdminName[MAXBUF];
68 char AdminEmail[MAXBUF];
69 char AdminNick[MAXBUF];
71 char restartpass[MAXBUF];
75 char PrefixQuit[MAXBUF];
76 char DieValue[MAXBUF];
77 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 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
86 unsigned int SoftLimit = MAXCLIENTS;
87 extern int MaxWhoResults;
91 char DisabledCommands[MAXBUF];
93 bool AllowHalfop = true;
94 bool AllowProtect = true;
95 bool AllowFounder = true;
97 extern std::vector<Module*> modules;
98 std::vector<std::string> module_names;
99 extern std::vector<ircd_module*> factory;
101 std::vector<InspSocket*> module_sockets;
104 int openSockfd[MAXSOCKS];
106 bool unlimitcore = false;
107 struct sockaddr_in client,server;
108 char addrs[MAXBUF][255];
110 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
112 extern InspSocket* socket_ref[65535];
114 time_t TIME = time(NULL), OLDTIME = time(NULL);
116 SocketEngine* SE = NULL;
118 bool has_been_netsplit = false;
119 extern std::vector<std::string> include_stack;
121 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
122 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
123 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
124 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
125 typedef std::deque<command_t> command_table;
126 typedef std::map<std::string,time_t> autoconnects;
127 typedef std::vector<std::string> servernamelist;
129 // This table references users by file descriptor.
130 // its an array to make it VERY fast, as all lookups are referenced
131 // by an integer, meaning there is no need for a scan/search operation.
132 userrec* fd_ref_table[65536];
134 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
136 Server* MyServer = new Server;
140 user_hash clientlist;
143 command_table cmdlist;
144 autoconnects autoconns;
150 servernamelist servernames;
152 struct linger linger = { 0 };
153 char MyExecutable[1024];
154 int boundPortCount = 0;
155 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
157 char ModPath[MAXBUF];
161 int has_channel(userrec *u, chanrec *c);
162 int usercount(chanrec *c);
163 int usercount_i(chanrec *c);
164 char* Passwd(userrec *user);
165 bool IsDenied(userrec *user);
166 void AddWhoWas(userrec* u);
168 std::stringstream config_f(stringstream::in | stringstream::out);
170 std::vector<userrec*> all_opers;
174 void AddOper(userrec* user)
176 log(DEBUG,"Oper added to optimization list");
177 all_opers.push_back(user);
180 void AddServerName(std::string servername)
182 log(DEBUG,"Adding server name: %s",servername.c_str());
183 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
185 if (*a == servername)
188 servernames.push_back(servername);
191 const char* FindServerNamePtr(std::string servername)
193 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
195 if (*a == servername)
198 AddServerName(servername);
199 return FindServerNamePtr(servername);
202 void DeleteOper(userrec* user)
204 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
208 log(DEBUG,"Oper removed from optimization list");
215 std::string GetRevision()
217 char Revision[] = "$Revision$";
220 char *v2 = strtok_r(s1," ",&savept);
222 v2 = strtok_r(s1," ",&savept);
224 return std::string(v2);
228 std::string getservername()
233 std::string getserverdesc()
238 std::string getnetworkname()
243 std::string getadminname()
248 std::string getadminemail()
253 std::string getadminnick()
258 void ReadConfig(bool bail, userrec* user)
260 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
261 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
263 std::stringstream errstr;
264 include_stack.clear();
266 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
269 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
272 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
280 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
281 while (!errstr.eof())
283 errstr.getline(dataline,1024);
284 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
289 WriteOpers("There were errors in the configuration file:");
290 while (!errstr.eof())
292 errstr.getline(dataline,1024);
293 WriteOpers(dataline);
300 ConfValue("server","name",0,ServerName,&config_f);
301 ConfValue("server","description",0,ServerDesc,&config_f);
302 ConfValue("server","network",0,Network,&config_f);
303 ConfValue("admin","name",0,AdminName,&config_f);
304 ConfValue("admin","email",0,AdminEmail,&config_f);
305 ConfValue("admin","nick",0,AdminNick,&config_f);
306 ConfValue("files","motd",0,motd,&config_f);
307 ConfValue("files","rules",0,rules,&config_f);
308 ConfValue("power","diepass",0,diepass,&config_f);
309 ConfValue("power","pause",0,pauseval,&config_f);
310 ConfValue("power","restartpass",0,restartpass,&config_f);
311 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
312 ConfValue("die","value",0,DieValue,&config_f);
313 ConfValue("options","loglevel",0,dbg,&config_f);
314 ConfValue("options","netbuffersize",0,NB,&config_f);
315 ConfValue("options","maxwho",0,MW,&config_f);
316 ConfValue("options","allowhalfop",0,AH,&config_f);
317 ConfValue("options","allowprotect",0,AP,&config_f);
318 ConfValue("options","allowfounder",0,AF,&config_f);
319 ConfValue("dns","server",0,DNSServer,&config_f);
320 ConfValue("dns","timeout",0,DNT,&config_f);
321 ConfValue("options","moduledir",0,ModPath,&config_f);
322 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
323 ConfValue("options","somaxconn",0,MCON,&config_f);
324 ConfValue("options","softlimit",0,SLIMT,&config_f);
326 SoftLimit = atoi(SLIMT);
327 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
329 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
330 SoftLimit = MAXCLIENTS;
332 MaxConn = atoi(MCON);
333 if (MaxConn > SOMAXCONN)
334 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
335 NetBufferSize = atoi(NB);
336 MaxWhoResults = atoi(MW);
337 dns_timeout = atoi(DNT);
343 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
345 strlcpy(ModPath,MOD_PATH,MAXBUF);
346 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
347 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
348 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
349 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
351 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
352 NetBufferSize = 10240;
354 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
356 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
359 if (!strcmp(dbg,"debug"))
361 if (!strcmp(dbg,"verbose"))
363 if (!strcmp(dbg,"default"))
365 if (!strcmp(dbg,"sparse"))
367 if (!strcmp(dbg,"none"))
370 log(DEFAULT,"Reading message of the day...");
371 readfile(RULES,rules);
372 log(DEFAULT,"Reading connect classes...");
374 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
377 ConfValue("connect","allow",i,Value,&config_f);
378 ConfValue("connect","timeout",i,timeout,&config_f);
379 ConfValue("connect","flood",i,flood,&config_f);
380 ConfValue("connect","pingfreq",i,pfreq,&config_f);
381 ConfValue("connect","threshold",i,thold,&config_f);
382 ConfValue("connect","sendq",i,sqmax,&config_f);
383 ConfValue("connect","recvq",i,rqmax,&config_f);
386 strlcpy(c.host,Value,MAXBUF);
388 strlcpy(Value,"",MAXBUF);
389 ConfValue("connect","password",i,Value,&config_f);
390 strlcpy(c.pass,Value,MAXBUF);
391 c.registration_timeout = 90; // default is 2 minutes
393 c.flood = atoi(flood);
395 c.sendqmax = 262144; // 256k
396 c.recvqmax = 4096; // 4k
399 c.threshold = atoi(thold);
403 c.sendqmax = atoi(sqmax);
407 c.recvqmax = atoi(rqmax);
411 c.registration_timeout = atoi(timeout);
415 c.pingtime = atoi(pfreq);
417 Classes.push_back(c);
418 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);
422 ConfValue("connect","deny",i,Value,&config_f);
423 strlcpy(c.host,Value,MAXBUF);
425 Classes.push_back(c);
426 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
430 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
431 read_xline_defaults();
432 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
436 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
438 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
439 ConfValue("link","name",i,Link_ServerName,&config_f);
440 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
441 if (strcmp(Link_AConn,""))
443 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
448 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
451 log(DEFAULT,"Adding and removing modules due to rehash...");
453 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
455 // store the old module names
456 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
458 old_module_names.push_back(*t);
461 // get the new module names
462 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
464 ConfValue("module","name",count2,Value,&config_f);
465 new_module_names.push_back(Value);
468 // now create a list of new modules that are due to be loaded
469 // and a seperate list of modules which are due to be unloaded
470 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
473 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
479 added_modules.push_back(*_new);
481 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
484 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
490 removed_modules.push_back(*oldm);
492 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
494 int rem = 0, add = 0;
495 if (!removed_modules.empty())
496 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
498 if (UnloadModule(removing->c_str()))
500 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
501 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
506 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
509 if (!added_modules.empty())
510 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
512 if (LoadModule(adding->c_str()))
514 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
515 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
520 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
523 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());
528 /* add a channel to a user, creating the record for it if needed and linking
529 * it to the user record */
531 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
533 if ((!user) || (!cn))
535 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
543 strncpy(cname,cn,MAXBUF);
545 // we MUST declare this wherever we use FOREACH_RESULT
548 if (strlen(cname) > CHANMAX)
550 cname[CHANMAX] = '\0';
553 log(DEBUG,"add_channel: %s %s",user->nick,cname);
555 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
557 return NULL; // already on the channel!
561 if (!FindChan(cname))
563 if (!strcasecmp(ServerName,user->server))
566 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
567 if (MOD_RESULT == 1) {
572 /* create a new one */
573 log(DEBUG,"add_channel: creating: %s",cname);
575 chanlist[cname] = new chanrec();
577 strlcpy(chanlist[cname]->name, cname,CHANMAX);
578 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
579 chanlist[cname]->created = TIME;
580 strcpy(chanlist[cname]->topic, "");
581 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
582 chanlist[cname]->topicset = 0;
583 Ptr = chanlist[cname];
584 log(DEBUG,"add_channel: created: %s",cname);
585 /* set created to 2 to indicate user
586 * is the first in the channel
587 * and should be given ops */
593 /* channel exists, just fish out a pointer to its struct */
594 Ptr = FindChan(cname);
597 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
599 // remote users are allowed us to bypass channel modes
600 // and bans (used by servers)
601 if (!strcasecmp(ServerName,user->server))
603 log(DEBUG,"Not overriding...");
605 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
606 if (MOD_RESULT == 1) {
609 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
613 log(DEBUG,"add_channel: checking key, invite, etc");
615 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
620 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
623 log(DEBUG,"add_channel: no key given in JOIN");
624 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
629 if (strcasecmp(key,Ptr->key))
631 log(DEBUG,"add_channel: bad key given in JOIN");
632 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
637 log(DEBUG,"add_channel: no key");
640 FOREACH_RESULT(OnCheckInvite(user, Ptr));
643 if (Ptr->binarymodes & CM_INVITEONLY)
645 log(DEBUG,"add_channel: channel is +i");
646 if (user->IsInvited(Ptr->name))
648 /* user was invited to channel */
649 /* there may be an optional channel NOTICE here */
653 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
657 log(DEBUG,"add_channel: channel is not +i");
660 FOREACH_RESULT(OnCheckLimit(user, Ptr));
665 if (usercount(Ptr) >= Ptr->limit)
667 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
672 log(DEBUG,"add_channel: about to walk banlist");
674 FOREACH_RESULT(OnCheckBan(user, Ptr));
677 /* check user against the channel banlist */
680 if (Ptr->bans.size())
682 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
684 if (match(user->GetFullHost(),i->data))
686 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
692 log(DEBUG,"add_channel: bans checked");
700 user->RemoveInvite(Ptr->name);
703 log(DEBUG,"add_channel: invites removed");
708 log(DEBUG,"Overridden checks");
716 log(DEBUG,"Passed channel checks");
718 for (int index =0; index != MAXCHANS; index++)
720 log(DEBUG,"Check location %d",index);
721 if (user->chans[index].channel == NULL)
723 log(DEBUG,"Adding into their channel list at location %d",index);
727 /* first user in is given ops */
728 user->chans[index].uc_modes = UCMODE_OP;
732 user->chans[index].uc_modes = 0;
734 user->chans[index].channel = Ptr;
735 Ptr->AddUser((char*)user);
736 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
738 log(DEBUG,"Sent JOIN to client");
742 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
743 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
746 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
747 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
748 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
749 FOREACH_MOD OnUserJoin(user,Ptr);
753 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
754 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
758 /* remove a channel from a users record, and remove the record from memory
759 * if the channel has become empty */
761 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
763 if ((!user) || (!cname))
765 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
771 if ((!cname) || (!user))
776 Ptr = FindChan(cname);
783 FOREACH_MOD OnUserPart(user,Ptr);
784 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
786 for (int i =0; i != MAXCHANS; i++)
788 /* zap it from the channel list of the user */
789 if (user->chans[i].channel == Ptr)
793 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
797 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
799 user->chans[i].uc_modes = 0;
800 user->chans[i].channel = NULL;
801 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
806 Ptr->DelUser((char*)user);
808 /* if there are no users left on the channel */
811 chan_hash::iterator iter = chanlist.find(Ptr->name);
813 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
815 /* kill the record */
816 if (iter != chanlist.end())
818 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
820 chanlist.erase(iter);
828 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
830 if ((!src) || (!user) || (!Ptr) || (!reason))
832 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
836 if ((!Ptr) || (!user) || (!src))
841 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
843 if (!has_channel(user,Ptr))
845 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
850 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
851 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
854 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
856 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
858 if (cstatus(src,Ptr) == STATUS_HOP)
860 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
864 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
871 if (!is_uline(src->server))
874 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
879 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
881 for (int i =0; i != MAXCHANS; i++)
883 /* zap it from the channel list of the user */
884 if (user->chans[i].channel)
885 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
887 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
888 user->chans[i].uc_modes = 0;
889 user->chans[i].channel = NULL;
890 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
895 Ptr->DelUser((char*)user);
897 /* if there are no users left on the channel */
900 chan_hash::iterator iter = chanlist.find(Ptr->name);
902 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
904 /* kill the record */
905 if (iter != chanlist.end())
907 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
909 chanlist.erase(iter);
917 /* This function pokes and hacks at a parameter list like the following:
919 * PART #winbot,#darkgalaxy :m00!
921 * to turn it into a series of individual calls like this:
924 * PART #darkgalaxy :m00!
926 * The seperate calls are sent to a callback function provided by the caller
927 * (the caller will usually call itself recursively). The callback function
928 * must be a command handler. Calling this function on a line with no list causes
929 * no action to be taken. You must provide a starting and ending parameter number
930 * where the range of the list can be found, useful if you have a terminating
931 * parameter as above which is actually not part of the list, or parameters
932 * before the actual list as well. This code is used by many functions which
933 * can function as "one to list" (see the RFC) */
935 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
940 char blog[32][MAXBUF];
941 char blog2[32][MAXBUF];
942 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
946 for (int i = 0; i <32; i++)
949 for (int i = 0; i <32; i++)
953 for (int i = 0; i <10; i++)
962 if (pcnt > 1) /* we have a key to copy */
964 strlcpy(keystr,parameters[1],MAXBUF);
968 if (!parameters[start])
972 if (!strchr(parameters[start],','))
977 for (int i = start; i <= end; i++)
981 strlcat(plist,parameters[i],MAXBUF);
989 for (int i = 0; i < t; i++)
994 strlcpy(blog[j++],param,MAXBUF);
998 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1003 strlcpy(blog[j++],param,MAXBUF);
1006 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1011 if ((joins) && (keystr))
1013 if (strchr(keystr,','))
1017 t2 = strlen(keystr);
1018 for (int i = 0; i < t2; i++)
1020 if (keystr[i] == ',')
1023 strlcpy(blog2[j++],param,MAXBUF);
1027 strlcpy(blog2[j++],param,MAXBUF);
1032 for (j = 0; j < total; j++)
1038 for (q = end; q < pcnt-1; q++)
1040 if (parameters[q+1])
1042 pars[q-end+1] = parameters[q+1];
1045 if ((joins) && (parameters[1]))
1056 /* repeatedly call the function with the hacked parameter list */
1057 if ((joins) && (pcnt > 1))
1061 // pars[1] already set up and containing key from blog2[j]
1066 pars[1] = parameters[1];
1072 fn(pars,pcnt-(end-start),u);
1081 void kill_link(userrec *user,const char* r)
1083 user_hash::iterator iter = clientlist.find(user->nick);
1085 char reason[MAXBUF];
1087 strncpy(reason,r,MAXBUF);
1089 if (strlen(reason)>MAXQUIT)
1091 reason[MAXQUIT-1] = '\0';
1094 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1095 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1096 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1098 if (user->registered == 7) {
1099 FOREACH_MOD OnUserQuit(user,reason);
1100 WriteCommonExcept(user,"QUIT :%s",reason);
1103 user->FlushWriteBuf();
1105 FOREACH_MOD OnUserDisconnect(user);
1109 FOREACH_MOD OnRawSocketClose(user->fd);
1110 SE->DelFd(user->fd);
1111 user->CloseSocket();
1114 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1115 // if they were an oper with +s.
1116 if (user->registered == 7) {
1117 purge_empty_chans(user);
1118 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1119 if (!strcmp(user->server,ServerName))
1120 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1124 if (iter != clientlist.end())
1126 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1128 fd_ref_table[user->fd] = NULL;
1129 clientlist.erase(iter);
1134 void kill_link_silent(userrec *user,const char* r)
1136 user_hash::iterator iter = clientlist.find(user->nick);
1138 char reason[MAXBUF];
1140 strncpy(reason,r,MAXBUF);
1142 if (strlen(reason)>MAXQUIT)
1144 reason[MAXQUIT-1] = '\0';
1147 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1148 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1149 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1151 user->FlushWriteBuf();
1153 if (user->registered == 7) {
1154 FOREACH_MOD OnUserQuit(user,reason);
1155 WriteCommonExcept(user,"QUIT :%s",reason);
1158 FOREACH_MOD OnUserDisconnect(user);
1162 FOREACH_MOD OnRawSocketClose(user->fd);
1163 SE->DelFd(user->fd);
1164 user->CloseSocket();
1167 if (user->registered == 7) {
1168 purge_empty_chans(user);
1171 if (iter != clientlist.end())
1173 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1175 fd_ref_table[user->fd] = NULL;
1176 clientlist.erase(iter);
1182 int main(int argc, char** argv)
1186 log(DEBUG,"*** InspIRCd starting up!");
1187 if (!FileExists(CONFIG_FILE))
1189 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1190 log(DEFAULT,"main: no config");
1191 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1195 for (int i = 1; i < argc; i++)
1197 if (!strcmp(argv[i],"-nofork")) {
1200 if (!strcmp(argv[i],"-wait")) {
1203 if (!strcmp(argv[i],"-nolimit")) {
1209 strlcpy(MyExecutable,argv[0],MAXBUF);
1211 // initialize the lowercase mapping table
1212 for (unsigned int cn = 0; cn < 256; cn++)
1214 // lowercase the uppercase chars
1215 for (unsigned int cn = 65; cn < 91; cn++)
1216 lowermap[cn] = tolower(cn);
1217 // now replace the specific chars for scandanavian comparison
1218 lowermap[(unsigned)'['] = '{';
1219 lowermap[(unsigned)']'] = '}';
1220 lowermap[(unsigned)'\\'] = '|';
1222 if (InspIRCd(argv,argc) == ERROR)
1224 log(DEFAULT,"main: daemon function bailed");
1225 printf("ERROR: could not initialise. Shutting down.\n");
1232 template<typename T> inline string ConvToStr(const T &in)
1235 if (!(tmp << in)) return string();
1239 /* re-allocates a nick in the user_hash after they change nicknames,
1240 * returns a pointer to the new user as it may have moved */
1242 userrec* ReHashNick(char* Old, char* New)
1244 //user_hash::iterator newnick;
1245 user_hash::iterator oldnick = clientlist.find(Old);
1247 log(DEBUG,"ReHashNick: %s %s",Old,New);
1249 if (!strcasecmp(Old,New))
1251 log(DEBUG,"old nick is new nick, skipping");
1252 return oldnick->second;
1255 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1257 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1259 userrec* olduser = oldnick->second;
1260 clientlist[New] = olduser;
1261 clientlist.erase(oldnick);
1263 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1265 return clientlist[New];
1268 /* adds or updates an entry in the whowas list */
1269 void AddWhoWas(userrec* u)
1271 whowas_hash::iterator iter = whowas.find(u->nick);
1272 WhoWasUser *a = new WhoWasUser();
1273 strlcpy(a->nick,u->nick,NICKMAX);
1274 strlcpy(a->ident,u->ident,IDENTMAX);
1275 strlcpy(a->dhost,u->dhost,160);
1276 strlcpy(a->host,u->host,160);
1277 strlcpy(a->fullname,u->fullname,MAXGECOS);
1278 strlcpy(a->server,u->server,256);
1279 a->signon = u->signon;
1281 /* MAX_WHOWAS: max number of /WHOWAS items
1282 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1283 * can be replaced by a newer one
1286 if (iter == whowas.end())
1288 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1290 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1292 // 3600 seconds in an hour ;)
1293 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1295 // delete the old one
1296 if (i->second) delete i->second;
1297 // replace with new one
1299 log(DEBUG,"added WHOWAS entry, purged an old record");
1303 // no space left and user doesnt exist. Don't leave ram in use!
1304 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1309 log(DEBUG,"added fresh WHOWAS entry");
1310 whowas[a->nick] = a;
1315 log(DEBUG,"updated WHOWAS entry");
1316 if (iter->second) delete iter->second;
1322 void* dns_task(void* arg)
1324 userrec* u = (userrec*)arg;
1325 log(DEBUG,"DNS thread for user %s",u->nick);
1330 if (dns1.ReverseLookup(u->ip))
1332 log(DEBUG,"DNS Step 1");
1333 while (!dns1.HasResult())
1337 host = dns1.GetResult();
1340 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1341 if (dns2.ForwardLookup(host))
1343 while (!dns2.HasResult())
1347 ip = dns2.GetResultIP();
1348 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1349 if (ip == std::string(u->ip))
1351 log(DEBUG,"DNS Step 4");
1352 if (host.length() < 160)
1354 log(DEBUG,"DNS Step 5");
1355 strcpy(u->host,host.c_str());
1356 strcpy(u->dhost,host.c_str());
1367 /* add a client connection to the sockets list */
1368 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1372 user_hash::iterator iter;
1374 tempnick = ConvToStr(socket) + "-unknown";
1375 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1377 iter = clientlist.find(tempnick);
1380 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1381 // using one as a registered connection. As theyre per fd, we can also safely assume
1382 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1383 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1384 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1385 // issue in earlier alphas/betas
1386 if (iter != clientlist.end())
1388 userrec* goner = iter->second;
1390 clientlist.erase(iter);
1394 * It is OK to access the value here this way since we know
1395 * it exists, we just created it above.
1397 * At NO other time should you access a value in a map or a
1398 * hash_map this way.
1400 clientlist[tempnick] = new userrec();
1402 NonBlocking(socket);
1403 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1405 clientlist[tempnick]->fd = socket;
1406 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1407 strlcpy(clientlist[tempnick]->host, host,160);
1408 strlcpy(clientlist[tempnick]->dhost, host,160);
1409 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1410 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1411 clientlist[tempnick]->registered = 0;
1412 clientlist[tempnick]->signon = TIME+dns_timeout;
1413 clientlist[tempnick]->lastping = 1;
1414 clientlist[tempnick]->port = port;
1415 strlcpy(clientlist[tempnick]->ip,ip,16);
1417 // set the registration timeout for this user
1418 unsigned long class_regtimeout = 90;
1419 int class_flood = 0;
1420 long class_threshold = 5;
1421 long class_sqmax = 262144; // 256kb
1422 long class_rqmax = 4096; // 4k
1424 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1426 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1428 class_regtimeout = (unsigned long)i->registration_timeout;
1429 class_flood = i->flood;
1430 clientlist[tempnick]->pingmax = i->pingtime;
1431 class_threshold = i->threshold;
1432 class_sqmax = i->sendqmax;
1433 class_rqmax = i->recvqmax;
1438 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1439 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1440 clientlist[tempnick]->flood = class_flood;
1441 clientlist[tempnick]->threshold = class_threshold;
1442 clientlist[tempnick]->sendqmax = class_sqmax;
1443 clientlist[tempnick]->recvqmax = class_rqmax;
1445 for (int i = 0; i < MAXCHANS; i++)
1447 clientlist[tempnick]->chans[i].channel = NULL;
1448 clientlist[tempnick]->chans[i].uc_modes = 0;
1451 if (clientlist.size() > SoftLimit)
1453 kill_link(clientlist[tempnick],"No more connections allowed");
1457 if (clientlist.size() >= MAXCLIENTS)
1459 kill_link(clientlist[tempnick],"No more connections allowed");
1463 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1464 // its a pretty big but for the moment valid assumption:
1465 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1466 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1467 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1468 // which for the time being is a physical impossibility (even the largest networks dont have more
1469 // than about 10,000 users on ONE server!)
1470 if ((unsigned)socket > 65534)
1472 kill_link(clientlist[tempnick],"Server is full");
1477 char* e = matches_exception(ip);
1480 char* r = matches_zline(ip);
1483 char reason[MAXBUF];
1484 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1485 kill_link(clientlist[tempnick],reason);
1489 fd_ref_table[socket] = clientlist[tempnick];
1490 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1493 /* shows the message of the day, and any other on-logon stuff */
1494 void FullConnectUser(userrec* user)
1497 user->idle_lastmsg = TIME;
1498 log(DEBUG,"ConnectUser: %s",user->nick);
1500 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1502 kill_link(user,"Invalid password");
1507 kill_link(user,"Unauthorised connection");
1511 char match_against[MAXBUF];
1512 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1513 char* e = matches_exception(match_against);
1516 char* r = matches_gline(match_against);
1519 char reason[MAXBUF];
1520 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1521 kill_link_silent(user,reason);
1524 r = matches_kline(user->host);
1527 char reason[MAXBUF];
1528 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1529 kill_link_silent(user,reason);
1535 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1536 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1537 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1538 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1539 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1540 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1541 std::stringstream v;
1542 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1543 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1544 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1546 std::string data005 = v.str();
1547 FOREACH_MOD On005Numeric(data005);
1548 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1549 // so i'd better split it :)
1550 std::stringstream out(data005);
1551 std::string token = "";
1552 std::string line5 = "";
1553 int token_counter = 0;
1557 line5 = line5 + token + " ";
1559 if ((token_counter >= 13) || (out.eof() == true))
1561 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1568 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1569 // onto the network and produce 'fake direction'
1570 FOREACH_MOD OnUserConnect(user);
1571 FOREACH_MOD OnGlobalConnect(user);
1572 user->registered = 7;
1573 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1577 /* shows the message of the day, and any other on-logon stuff */
1578 void ConnectUser(userrec *user)
1580 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1581 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1583 FullConnectUser(user);
1587 std::string GetVersionString()
1589 char Revision[] = "$Revision$";
1590 char versiondata[MAXBUF];
1591 char *s1 = Revision;
1593 char *v2 = strtok_r(s1," ",&savept);
1595 v2 = strtok_r(s1," ",&savept);
1598 char dnsengine[] = "multithread";
1600 char dnsengine[] = "singlethread";
1602 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1606 void handle_version(char **parameters, int pcnt, userrec *user)
1608 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1612 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1614 for (unsigned int i = 0; i < cmdlist.size(); i++)
1616 if (!strcasecmp(cmdlist[i].command,commandname))
1618 if (cmdlist[i].handler_function)
1620 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1622 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1624 if (cmdlist[i].flags_needed)
1626 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1644 // calls a handler function for a command
1646 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1648 for (unsigned int i = 0; i < cmdlist.size(); i++)
1650 if (!strcasecmp(cmdlist[i].command,commandname))
1652 if (cmdlist[i].handler_function)
1654 if (pcnt>=cmdlist[i].min_params)
1656 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1658 if (cmdlist[i].flags_needed)
1660 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1662 cmdlist[i].handler_function(parameters,pcnt,user);
1667 cmdlist[i].handler_function(parameters,pcnt,user);
1677 void force_nickchange(userrec* user,const char* newnick)
1684 FOREACH_RESULT(OnUserPreNick(user,newnick));
1687 kill_link(user,"Nickname collision");
1690 if (matches_qline(newnick))
1693 kill_link(user,"Nickname collision");
1701 strncpy(nick,newnick,MAXBUF);
1703 if (user->registered == 7)
1707 handle_nick(pars,1,user);
1713 int process_parameters(char **command_p,char *parameters)
1716 int q = strlen(parameters);
1719 /* no parameters, command_p invalid! */
1722 if (parameters[0] == ':')
1724 command_p[0] = parameters+1;
1729 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1731 /* only one parameter */
1732 command_p[0] = parameters;
1733 if (parameters[0] == ':')
1735 if (strchr(parameters,' ') != NULL)
1743 command_p[j++] = parameters;
1744 for (int i = 0; i <= q; i++)
1746 if (parameters[i] == ' ')
1748 command_p[j++] = parameters+i+1;
1749 parameters[i] = '\0';
1750 if (command_p[j-1][0] == ':')
1752 *command_p[j-1]++; /* remove dodgy ":" */
1754 /* parameter like this marks end of the sequence */
1758 return j; /* returns total number of items in the list */
1761 void process_command(userrec *user, char* cmd)
1765 char *command_p[127];
1766 char p[MAXBUF], temp[MAXBUF];
1767 int j, items, cmd_found;
1769 for (int i = 0; i < 127; i++)
1770 command_p[i] = NULL;
1785 int total_params = 0;
1788 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1790 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1793 // found a 'trailing', we dont count them after this.
1801 // another phidjit bug...
1802 if (total_params > 126)
1804 *(strchr(cmd,' ')) = '\0';
1805 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1809 strlcpy(temp,cmd,MAXBUF);
1811 std::string tmp = cmd;
1812 for (int i = 0; i <= MODCOUNT; i++)
1814 std::string oldtmp = tmp;
1815 modules[i]->OnServerRaw(tmp,true,user);
1818 log(DEBUG,"A Module changed the input string!");
1819 log(DEBUG,"New string: %s",tmp.c_str());
1820 log(DEBUG,"Old string: %s",oldtmp.c_str());
1824 strlcpy(cmd,tmp.c_str(),MAXBUF);
1825 strlcpy(temp,cmd,MAXBUF);
1827 if (!strchr(cmd,' '))
1829 /* no parameters, lets skip the formalities and not chop up
1831 log(DEBUG,"About to preprocess command with no params");
1833 command_p[0] = NULL;
1835 for (unsigned int i = 0; i <= strlen(cmd); i++)
1837 cmd[i] = toupper(cmd[i]);
1845 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1846 for (unsigned int i = 0; i < strlen(temp); i++)
1848 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1854 /* split the full string into a command plus parameters */
1858 if (strchr(cmd,' '))
1860 for (unsigned int i = 0; i <= strlen(cmd); i++)
1862 /* capitalise the command ONLY, leave params intact */
1863 cmd[i] = toupper(cmd[i]);
1864 /* are we nearly there yet?! :P */
1868 parameters = cmd+i+1;
1876 for (unsigned int i = 0; i <= strlen(cmd); i++)
1878 cmd[i] = toupper(cmd[i]);
1885 if (strlen(command)>MAXCOMMAND)
1887 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1891 for (unsigned int x = 0; x < strlen(command); x++)
1893 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1895 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1897 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1900 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1907 for (unsigned int i = 0; i != cmdlist.size(); i++)
1909 if (cmdlist[i].command[0])
1911 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1917 items = process_parameters(command_p,parameters);
1922 command_p[0] = NULL;
1928 command_p[0] = NULL;
1933 /* activity resets the ping pending timer */
1934 user->nping = TIME + user->pingmax;
1935 if ((items) < cmdlist[i].min_params)
1937 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1938 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1941 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1943 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1944 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1948 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1950 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1951 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1955 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1957 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1959 if ((!isnick(user->nick)) || (user->registered != 7))
1961 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1962 WriteServ(user->fd,"451 %s :You have not registered",command);
1966 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1968 std::stringstream dcmds(DisabledCommands);
1969 while (!dcmds.eof())
1971 std::string thiscmd;
1973 if (!strcasecmp(thiscmd.c_str(),command))
1975 // command is disabled!
1976 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1981 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1983 if (cmdlist[i].handler_function)
1986 /* ikky /stats counters */
1989 cmdlist[i].use_count++;
1990 cmdlist[i].total_bytes+=strlen(temp);
1994 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1995 if (MOD_RESULT == 1) {
1999 /* WARNING: nothing may come after the
2000 * command handler call, as the handler
2001 * may free the user structure! */
2003 cmdlist[i].handler_function(command_p,items,user);
2009 WriteServ(user->fd,"451 %s :You have not registered",command);
2017 if ((!cmd_found) && (user))
2020 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2024 bool removecommands(const char* source)
2026 bool go_again = true;
2030 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2032 if (!strcmp(i->source,source))
2034 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2045 void process_buffer(const char* cmdbuf,userrec *user)
2049 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2055 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2062 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2064 strlcpy(cmd,cmdbuf,MAXBUF);
2069 int sl = strlen(cmd)-1;
2070 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2075 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2080 while (cmd[sl] == ' ') // strip trailing spaces
2090 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2092 if ((user) && (cmd))
2094 process_command(user,cmd);
2098 char MODERR[MAXBUF];
2105 void erase_factory(int j)
2108 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2113 factory.push_back(NULL);
2120 void erase_module(int j)
2123 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2129 modules.push_back(NULL);
2135 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2139 module_names.erase(v);
2147 bool UnloadModule(const char* filename)
2149 std::string filename_str = filename;
2150 for (unsigned int j = 0; j != module_names.size(); j++)
2152 if (module_names[j] == filename_str)
2154 if (modules[j]->GetVersion().Flags & VF_STATIC)
2156 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2157 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2160 /* Give the module a chance to tidy out all its metadata */
2161 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2163 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2165 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2167 modules[j]->OnCleanup(TYPE_USER,u->second);
2169 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2171 log(DEBUG,"Deleting module...");
2173 log(DEBUG,"Erasing module entry...");
2175 log(DEBUG,"Removing dependent commands...");
2176 removecommands(filename);
2177 log(DEFAULT,"Module %s unloaded",filename);
2182 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2183 snprintf(MODERR,MAXBUF,"Module not loaded");
2187 bool LoadModule(const char* filename)
2189 char modfile[MAXBUF];
2191 snprintf(modfile,MAXBUF,"%s",filename);
2193 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2195 std::string filename_str = filename;
2197 if (!DirValid(modfile))
2199 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2200 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2204 log(DEBUG,"Loading module: %s",modfile);
2206 if (FileExists(modfile))
2209 for (unsigned int j = 0; j < module_names.size(); j++)
2211 if (module_names[j] == filename_str)
2213 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2214 snprintf(MODERR,MAXBUF,"Module already loaded");
2218 ircd_module* a = new ircd_module(modfile);
2219 factory[MODCOUNT+1] = a;
2220 if (factory[MODCOUNT+1]->LastError())
2222 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2223 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2227 if (factory[MODCOUNT+1]->factory)
2229 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2230 modules[MODCOUNT+1] = m;
2231 /* save the module and the module's classfactory, if
2232 * this isnt done, random crashes can occur :/ */
2233 module_names.push_back(filename);
2237 log(DEFAULT,"Unable to load %s",modfile);
2238 snprintf(MODERR,MAXBUF,"Factory function failed!");
2245 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2246 snprintf(MODERR,MAXBUF,"Module file could not be found");
2251 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2257 int clientportcount = 0;
2258 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2260 ConfValue("bind","port",count,configToken,&config_f);
2261 ConfValue("bind","address",count,Addr,&config_f);
2262 ConfValue("bind","type",count,Type,&config_f);
2263 if (strcmp(Type,"servers"))
2265 // modules handle server bind types now,
2266 // its not a typo in the strcmp.
2267 ports[clientportcount] = atoi(configToken);
2268 strlcpy(addrs[clientportcount],Addr,256);
2270 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2273 portCount = clientportcount;
2275 for (int count = 0; count < portCount; count++)
2277 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2279 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2282 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2284 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2286 else /* well we at least bound to one socket so we'll continue */
2292 /* if we didn't bind to anything then abort */
2293 if (!boundPortCount)
2295 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2296 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2300 return boundPortCount;
2303 int InspIRCd(char** argv, int argc)
2305 bool expire_run = false;
2306 std::vector<int> activefds;
2309 InspSocket* s = NULL;
2310 InspSocket* s_del = NULL;
2311 char target[MAXBUF];
2312 unsigned int numberactive;
2314 /* Beta 7 moved all this stuff out of the main function
2315 * into smaller sub-functions, much tidier -- Brain
2317 OpenLog(argv, argc);
2319 SetupCommandTable();
2320 ReadConfig(true,NULL);
2321 AddServerName(ServerName);
2323 boundPortCount = BindPorts();
2326 startup_time = time(NULL);
2329 ConfValue("pid","file",0,PID,&config_f);
2330 // write once here, to try it out and make sure its ok
2335 if (DaemonSeed() == ERROR)
2337 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2342 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2343 * initialize the socket engine.
2345 SE = new SocketEngine();
2347 /* We must load the modules AFTER initializing the socket engine, now */
2350 printf("\nInspIRCd is now running!\n");
2353 freopen("/dev/null","w",stdout);
2354 freopen("/dev/null","w",stderr);
2357 /* Add the listening sockets used for client inbound connections
2358 * to the socket engine
2360 for (int count = 0; count < portCount; count++)
2361 SE->AddFd(openSockfd[count],true,X_LISTEN);
2365 /* main loop, this never returns */
2368 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2369 * Once per loop iteration is pleanty.
2374 /* Run background module timers every few seconds
2375 * (the docs say modules shouldnt rely on accurate
2376 * timing using this event, so we dont have to
2377 * time this exactly).
2379 if (((TIME % 8) == 0) && (!expire_run))
2382 FOREACH_MOD OnBackgroundTimer(TIME);
2386 if ((TIME % 8) == 1)
2389 /* Once a second, do the background processing */
2390 if (TIME != OLDTIME)
2391 while (DoBackgroundUserStuff(TIME));
2393 /* Call the socket engine to wait on the active
2394 * file descriptors. The socket engine has everything's
2395 * descriptors in its list... dns, modules, users,
2396 * servers... so its nice and easy, just one call.
2398 SE->Wait(activefds);
2401 * Now process each of the fd's. For users, we have a fast
2402 * lookup table which can find a user by file descriptor, so
2403 * processing them by fd isnt expensive. If we have a lot of
2404 * listening ports or module sockets though, things could get
2407 numberactive = activefds.size();
2408 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2410 int socket_type = SE->GetType(activefds[activefd]);
2411 switch (socket_type)
2413 case X_ESTAB_CLIENT:
2415 cu = fd_ref_table[activefds[activefd]];
2421 case X_ESTAB_MODULE:
2423 /* Process module-owned sockets.
2424 * Modules are encouraged to inherit their sockets from
2425 * InspSocket so we can process them neatly like this.
2427 s = socket_ref[activefds[activefd]];
2429 if ((s) && (!s->Poll()))
2431 log(DEBUG,"Socket poll returned false, close and bail");
2432 SE->DelFd(s->GetFd());
2433 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2435 s_del = (InspSocket*)*a;
2436 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2438 module_sockets.erase(a);
2450 /* When we are using single-threaded dns,
2451 * the sockets for dns end up in our mainloop.
2452 * When we are using multi-threaded dns,
2453 * each thread has its own basic poll() loop
2454 * within it, making them 'fire and forget'
2455 * and independent of the mainloop.
2457 log(DEBUG,"Got a ready socket of type X_ESTAB_DNS");
2458 #ifndef THREADED_DNS
2459 dns_poll(activefds[activefd]);
2465 /* It's a listener */
2466 for (int count = 0; count < boundPortCount; count++)
2468 if (activefds[activefd] == openSockfd[count])
2470 length = sizeof (client);
2471 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2472 log(DEBUG,"Accepted socket %d",incomingSockfd);
2473 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2474 /* Years and years ago, we used to resolve here
2475 * using gethostbyaddr(). That is sucky and we
2476 * don't do that any more...
2478 if (incomingSockfd >= 0)
2480 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, ports[count]);
2482 AddClient(incomingSockfd, target, ports[count], false, inet_ntoa (client.sin_addr));
2483 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2487 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)ports[count],target);
2488 log(DEBUG,"accept failed: %lu",(unsigned long)ports[count]);
2491 /* We've found out what port it belongs on,
2492 * no need to iterate the rest
2500 /* Something went wrong if we're in here.
2501 * In fact, so wrong, im not quite sure
2502 * what we would do, so for now, its going
2503 * to safely do bugger all.
2510 /* This is never reached -- we hope! */