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"
60 #include "userprocess.h"
64 int LogLevel = DEFAULT;
65 char ServerName[MAXBUF];
67 char ServerDesc[MAXBUF];
68 char AdminName[MAXBUF];
69 char AdminEmail[MAXBUF];
70 char AdminNick[MAXBUF];
72 char restartpass[MAXBUF];
76 char PrefixQuit[MAXBUF];
77 char DieValue[MAXBUF];
78 char DNSServer[MAXBUF];
81 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
82 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
84 time_t startup_time = time(NULL);
85 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
86 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
87 unsigned int SoftLimit = MAXCLIENTS;
88 extern int MaxWhoResults;
92 char DisabledCommands[MAXBUF];
94 bool AllowHalfop = true;
95 bool AllowProtect = true;
96 bool AllowFounder = true;
98 extern std::vector<Module*> modules;
99 std::vector<std::string> module_names;
100 extern std::vector<ircd_module*> factory;
102 std::vector<InspSocket*> module_sockets;
105 int openSockfd[MAXSOCKS];
107 bool unlimitcore = false;
108 struct sockaddr_in client,server;
109 char addrs[MAXBUF][255];
111 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
113 extern InspSocket* socket_ref[65535];
115 time_t TIME = time(NULL), OLDTIME = time(NULL);
117 SocketEngine* SE = NULL;
119 bool has_been_netsplit = false;
120 extern std::vector<std::string> include_stack;
122 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
123 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
124 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
125 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
126 typedef std::deque<command_t> command_table;
127 typedef std::map<std::string,time_t> autoconnects;
128 typedef std::vector<std::string> servernamelist;
130 // This table references users by file descriptor.
131 // its an array to make it VERY fast, as all lookups are referenced
132 // by an integer, meaning there is no need for a scan/search operation.
133 userrec* fd_ref_table[65536];
135 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
137 Server* MyServer = new Server;
141 user_hash clientlist;
144 command_table cmdlist;
145 autoconnects autoconns;
151 servernamelist servernames;
153 struct linger linger = { 0 };
154 char MyExecutable[1024];
155 int boundPortCount = 0;
156 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
158 char ModPath[MAXBUF];
162 int has_channel(userrec *u, chanrec *c);
163 int usercount(chanrec *c);
164 int usercount_i(chanrec *c);
165 char* Passwd(userrec *user);
166 bool IsDenied(userrec *user);
167 void AddWhoWas(userrec* u);
169 std::stringstream config_f(stringstream::in | stringstream::out);
171 std::vector<userrec*> all_opers;
175 void AddOper(userrec* user)
177 log(DEBUG,"Oper added to optimization list");
178 all_opers.push_back(user);
181 void AddServerName(std::string servername)
183 log(DEBUG,"Adding server name: %s",servername.c_str());
184 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
186 if (*a == servername)
189 servernames.push_back(servername);
192 const char* FindServerNamePtr(std::string servername)
194 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
196 if (*a == servername)
199 AddServerName(servername);
200 return FindServerNamePtr(servername);
203 void DeleteOper(userrec* user)
205 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
209 log(DEBUG,"Oper removed from optimization list");
216 std::string GetRevision()
218 /* w00t got me to replace a bunch of strtok_r
219 * with something nicer, so i did this. Its the
220 * same thing really, only in C++. It places the
221 * text into a std::stringstream which is a readable
222 * and writeable buffer stream, and then pops two
223 * words off it, space delimited. Because it reads
224 * into the same variable twice, the first word
225 * is discarded, and the second one returned.
227 std::stringstream Revision("$Revision$");
229 Revision >> single >> single;
234 std::string getservername()
239 std::string getserverdesc()
244 std::string getnetworkname()
249 std::string getadminname()
254 std::string getadminemail()
259 std::string getadminnick()
264 void ReadConfig(bool bail, userrec* user)
266 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
267 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
269 std::stringstream errstr;
270 include_stack.clear();
272 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
275 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
278 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
286 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
287 while (!errstr.eof())
289 errstr.getline(dataline,1024);
290 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
295 WriteOpers("There were errors in the configuration file:");
296 while (!errstr.eof())
298 errstr.getline(dataline,1024);
299 WriteOpers(dataline);
306 ConfValue("server","name",0,ServerName,&config_f);
307 ConfValue("server","description",0,ServerDesc,&config_f);
308 ConfValue("server","network",0,Network,&config_f);
309 ConfValue("admin","name",0,AdminName,&config_f);
310 ConfValue("admin","email",0,AdminEmail,&config_f);
311 ConfValue("admin","nick",0,AdminNick,&config_f);
312 ConfValue("files","motd",0,motd,&config_f);
313 ConfValue("files","rules",0,rules,&config_f);
314 ConfValue("power","diepass",0,diepass,&config_f);
315 ConfValue("power","pause",0,pauseval,&config_f);
316 ConfValue("power","restartpass",0,restartpass,&config_f);
317 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
318 ConfValue("die","value",0,DieValue,&config_f);
319 ConfValue("options","loglevel",0,dbg,&config_f);
320 ConfValue("options","netbuffersize",0,NB,&config_f);
321 ConfValue("options","maxwho",0,MW,&config_f);
322 ConfValue("options","allowhalfop",0,AH,&config_f);
323 ConfValue("options","allowprotect",0,AP,&config_f);
324 ConfValue("options","allowfounder",0,AF,&config_f);
325 ConfValue("dns","server",0,DNSServer,&config_f);
326 ConfValue("dns","timeout",0,DNT,&config_f);
327 ConfValue("options","moduledir",0,ModPath,&config_f);
328 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
329 ConfValue("options","somaxconn",0,MCON,&config_f);
330 ConfValue("options","softlimit",0,SLIMT,&config_f);
332 SoftLimit = atoi(SLIMT);
333 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
335 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
336 SoftLimit = MAXCLIENTS;
338 MaxConn = atoi(MCON);
339 if (MaxConn > SOMAXCONN)
340 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
341 NetBufferSize = atoi(NB);
342 MaxWhoResults = atoi(MW);
343 dns_timeout = atoi(DNT);
349 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
351 strlcpy(ModPath,MOD_PATH,MAXBUF);
352 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
353 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
354 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
355 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
357 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
358 NetBufferSize = 10240;
360 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
362 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
365 if (!strcmp(dbg,"debug"))
367 if (!strcmp(dbg,"verbose"))
369 if (!strcmp(dbg,"default"))
371 if (!strcmp(dbg,"sparse"))
373 if (!strcmp(dbg,"none"))
376 log(DEFAULT,"Reading message of the day...");
377 readfile(RULES,rules);
378 log(DEFAULT,"Reading connect classes...");
380 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
383 ConfValue("connect","allow",i,Value,&config_f);
384 ConfValue("connect","timeout",i,timeout,&config_f);
385 ConfValue("connect","flood",i,flood,&config_f);
386 ConfValue("connect","pingfreq",i,pfreq,&config_f);
387 ConfValue("connect","threshold",i,thold,&config_f);
388 ConfValue("connect","sendq",i,sqmax,&config_f);
389 ConfValue("connect","recvq",i,rqmax,&config_f);
392 strlcpy(c.host,Value,MAXBUF);
394 strlcpy(Value,"",MAXBUF);
395 ConfValue("connect","password",i,Value,&config_f);
396 strlcpy(c.pass,Value,MAXBUF);
397 c.registration_timeout = 90; // default is 2 minutes
399 c.flood = atoi(flood);
401 c.sendqmax = 262144; // 256k
402 c.recvqmax = 4096; // 4k
405 c.threshold = atoi(thold);
409 c.sendqmax = atoi(sqmax);
413 c.recvqmax = atoi(rqmax);
417 c.registration_timeout = atoi(timeout);
421 c.pingtime = atoi(pfreq);
423 Classes.push_back(c);
424 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);
428 ConfValue("connect","deny",i,Value,&config_f);
429 strlcpy(c.host,Value,MAXBUF);
431 Classes.push_back(c);
432 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
436 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
437 read_xline_defaults();
438 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
442 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
444 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
445 ConfValue("link","name",i,Link_ServerName,&config_f);
446 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
447 if (strcmp(Link_AConn,""))
449 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
454 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
457 log(DEFAULT,"Adding and removing modules due to rehash...");
459 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
461 // store the old module names
462 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
464 old_module_names.push_back(*t);
467 // get the new module names
468 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
470 ConfValue("module","name",count2,Value,&config_f);
471 new_module_names.push_back(Value);
474 // now create a list of new modules that are due to be loaded
475 // and a seperate list of modules which are due to be unloaded
476 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
479 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
485 added_modules.push_back(*_new);
487 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
490 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
496 removed_modules.push_back(*oldm);
498 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
500 int rem = 0, add = 0;
501 if (!removed_modules.empty())
502 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
504 if (UnloadModule(removing->c_str()))
506 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
507 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
512 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
515 if (!added_modules.empty())
516 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
518 if (LoadModule(adding->c_str()))
520 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
521 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
526 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
529 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());
534 /* add a channel to a user, creating the record for it if needed and linking
535 * it to the user record */
537 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
539 if ((!user) || (!cn))
541 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
548 strncpy(cname,cn,CHANMAX);
550 log(DEBUG,"add_channel: %s %s",user->nick,cname);
552 chanrec* Ptr = FindChan(cname);
559 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
563 /* create a new one */
564 chanlist[cname] = new chanrec();
565 strlcpy(chanlist[cname]->name, cname,CHANMAX);
566 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
567 chanlist[cname]->created = TIME;
568 strcpy(chanlist[cname]->topic, "");
569 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
570 chanlist[cname]->topicset = 0;
571 Ptr = chanlist[cname];
572 log(DEBUG,"add_channel: created: %s",cname);
573 /* set created to 2 to indicate user
574 * is the first in the channel
575 * and should be given ops */
580 /* Already on the channel */
581 if (has_channel(user,Ptr))
584 // remote users are allowed us to bypass channel modes
585 // and bans (used by servers)
589 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
590 if (MOD_RESULT == 1) {
598 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
603 log(DEBUG,"add_channel: no key given in JOIN");
604 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
609 if (strcasecmp(key,Ptr->key))
611 log(DEBUG,"add_channel: bad key given in JOIN");
612 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
618 if (Ptr->binarymodes & CM_INVITEONLY)
621 FOREACH_RESULT(OnCheckInvite(user, Ptr));
624 log(DEBUG,"add_channel: channel is +i");
625 if (user->IsInvited(Ptr->name))
627 /* user was invited to channel */
628 /* there may be an optional channel NOTICE here */
632 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
636 user->RemoveInvite(Ptr->name);
641 FOREACH_RESULT(OnCheckLimit(user, Ptr));
644 if (usercount(Ptr) >= Ptr->limit)
646 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
651 if (Ptr->bans.size())
653 log(DEBUG,"add_channel: about to walk banlist");
655 FOREACH_RESULT(OnCheckBan(user, Ptr));
658 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
660 if (match(user->GetFullHost(),i->data))
662 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
672 log(DEBUG,"Overridden checks");
677 log(DEBUG,"Passed channel checks");
679 for (unsigned int index =0; index < user->chans.size(); index++)
681 if (user->chans[index].channel == NULL)
683 return ForceChan(Ptr,user->chans[index],user,created);
686 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
687 * and put the channel in here. Same for remote users which are not bound by
688 * the channel limits. Otherwise, nope, youre boned.
693 chanrec* c = ForceChan(Ptr,a,user,created);
694 user->chans.push_back(a);
697 else if (strchr(user->modes,'o'))
699 /* Oper allows extension up to the OPERMAXCHANS value */
700 if (user->chans.size() < OPERMAXCHANS)
703 chanrec* c = ForceChan(Ptr,a,user,created);
704 user->chans.push_back(a);
708 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
709 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
713 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
717 /* first user in is given ops */
718 a.uc_modes = UCMODE_OP;
725 Ptr->AddUser((char*)user);
726 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
727 log(DEBUG,"Sent JOIN to client");
730 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
731 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
734 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
735 FOREACH_MOD OnUserJoin(user,Ptr);
739 /* remove a channel from a users record, and remove the record from memory
740 * if the channel has become empty */
742 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
744 if ((!user) || (!cname))
746 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
750 chanrec* Ptr = FindChan(cname);
755 FOREACH_MOD OnUserPart(user,Ptr);
756 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
758 for (unsigned int i =0; i < user->chans.size(); i++)
760 /* zap it from the channel list of the user */
761 if (user->chans[i].channel == Ptr)
765 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
769 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
771 user->chans[i].uc_modes = 0;
772 user->chans[i].channel = NULL;
773 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
778 Ptr->DelUser((char*)user);
780 /* if there are no users left on the channel */
783 chan_hash::iterator iter = chanlist.find(Ptr->name);
785 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
787 /* kill the record */
788 if (iter != chanlist.end())
790 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
792 chanlist.erase(iter);
800 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
802 if ((!src) || (!user) || (!Ptr) || (!reason))
804 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
808 if ((!Ptr) || (!user) || (!src))
813 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
815 if (!has_channel(user,Ptr))
817 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
822 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
823 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
826 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
828 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
830 if (cstatus(src,Ptr) == STATUS_HOP)
832 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
836 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
843 if (!is_uline(src->server))
846 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
851 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
853 for (unsigned int i =0; i < user->chans.size(); i++)
855 /* zap it from the channel list of the user */
856 if (user->chans[i].channel)
857 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
859 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
860 user->chans[i].uc_modes = 0;
861 user->chans[i].channel = NULL;
862 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
867 Ptr->DelUser((char*)user);
869 /* if there are no users left on the channel */
872 chan_hash::iterator iter = chanlist.find(Ptr->name);
874 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
876 /* kill the record */
877 if (iter != chanlist.end())
879 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
881 chanlist.erase(iter);
889 /* This function pokes and hacks at a parameter list like the following:
891 * PART #winbot,#darkgalaxy :m00!
893 * to turn it into a series of individual calls like this:
896 * PART #darkgalaxy :m00!
898 * The seperate calls are sent to a callback function provided by the caller
899 * (the caller will usually call itself recursively). The callback function
900 * must be a command handler. Calling this function on a line with no list causes
901 * no action to be taken. You must provide a starting and ending parameter number
902 * where the range of the list can be found, useful if you have a terminating
903 * parameter as above which is actually not part of the list, or parameters
904 * before the actual list as well. This code is used by many functions which
905 * can function as "one to list" (see the RFC) */
907 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
912 char blog[32][MAXBUF];
913 char blog2[32][MAXBUF];
914 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
918 for (int i = 0; i <32; i++)
921 for (int i = 0; i <32; i++)
925 for (int i = 0; i <10; i++)
934 if (pcnt > 1) /* we have a key to copy */
936 strlcpy(keystr,parameters[1],MAXBUF);
940 if (!parameters[start])
944 if (!strchr(parameters[start],','))
949 for (int i = start; i <= end; i++)
953 strlcat(plist,parameters[i],MAXBUF);
961 for (int i = 0; i < t; i++)
966 strlcpy(blog[j++],param,MAXBUF);
970 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
975 strlcpy(blog[j++],param,MAXBUF);
978 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
983 if ((joins) && (keystr))
985 if (strchr(keystr,','))
990 for (int i = 0; i < t2; i++)
992 if (keystr[i] == ',')
995 strlcpy(blog2[j++],param,MAXBUF);
999 strlcpy(blog2[j++],param,MAXBUF);
1004 for (j = 0; j < total; j++)
1010 for (q = end; q < pcnt-1; q++)
1012 if (parameters[q+1])
1014 pars[q-end+1] = parameters[q+1];
1017 if ((joins) && (parameters[1]))
1028 /* repeatedly call the function with the hacked parameter list */
1029 if ((joins) && (pcnt > 1))
1033 // pars[1] already set up and containing key from blog2[j]
1038 pars[1] = parameters[1];
1044 fn(pars,pcnt-(end-start),u);
1053 void kill_link(userrec *user,const char* r)
1055 user_hash::iterator iter = clientlist.find(user->nick);
1057 char reason[MAXBUF];
1059 strncpy(reason,r,MAXBUF);
1061 if (strlen(reason)>MAXQUIT)
1063 reason[MAXQUIT-1] = '\0';
1066 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1067 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1068 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1070 if (user->registered == 7) {
1071 FOREACH_MOD OnUserQuit(user,reason);
1072 WriteCommonExcept(user,"QUIT :%s",reason);
1075 user->FlushWriteBuf();
1077 FOREACH_MOD OnUserDisconnect(user);
1081 FOREACH_MOD OnRawSocketClose(user->fd);
1082 SE->DelFd(user->fd);
1083 user->CloseSocket();
1086 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1087 // if they were an oper with +s.
1088 if (user->registered == 7) {
1089 purge_empty_chans(user);
1090 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1092 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1096 if (iter != clientlist.end())
1098 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1100 fd_ref_table[user->fd] = NULL;
1101 clientlist.erase(iter);
1106 void kill_link_silent(userrec *user,const char* r)
1108 user_hash::iterator iter = clientlist.find(user->nick);
1110 char reason[MAXBUF];
1112 strncpy(reason,r,MAXBUF);
1114 if (strlen(reason)>MAXQUIT)
1116 reason[MAXQUIT-1] = '\0';
1119 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1120 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1121 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1123 user->FlushWriteBuf();
1125 if (user->registered == 7) {
1126 FOREACH_MOD OnUserQuit(user,reason);
1127 WriteCommonExcept(user,"QUIT :%s",reason);
1130 FOREACH_MOD OnUserDisconnect(user);
1134 FOREACH_MOD OnRawSocketClose(user->fd);
1135 SE->DelFd(user->fd);
1136 user->CloseSocket();
1139 if (user->registered == 7) {
1140 purge_empty_chans(user);
1143 if (iter != clientlist.end())
1145 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1147 fd_ref_table[user->fd] = NULL;
1148 clientlist.erase(iter);
1154 int main(int argc, char** argv)
1158 log(DEBUG,"*** InspIRCd starting up!");
1159 if (!FileExists(CONFIG_FILE))
1161 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1162 log(DEFAULT,"main: no config");
1163 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1167 for (int i = 1; i < argc; i++)
1169 if (!strcmp(argv[i],"-nofork")) {
1172 if (!strcmp(argv[i],"-wait")) {
1175 if (!strcmp(argv[i],"-nolimit")) {
1181 strlcpy(MyExecutable,argv[0],MAXBUF);
1183 // initialize the lowercase mapping table
1184 for (unsigned int cn = 0; cn < 256; cn++)
1186 // lowercase the uppercase chars
1187 for (unsigned int cn = 65; cn < 91; cn++)
1188 lowermap[cn] = tolower(cn);
1189 // now replace the specific chars for scandanavian comparison
1190 lowermap[(unsigned)'['] = '{';
1191 lowermap[(unsigned)']'] = '}';
1192 lowermap[(unsigned)'\\'] = '|';
1194 if (InspIRCd(argv,argc) == ERROR)
1196 log(DEFAULT,"main: daemon function bailed");
1197 printf("ERROR: could not initialise. Shutting down.\n");
1204 template<typename T> inline string ConvToStr(const T &in)
1207 if (!(tmp << in)) return string();
1211 /* re-allocates a nick in the user_hash after they change nicknames,
1212 * returns a pointer to the new user as it may have moved */
1214 userrec* ReHashNick(char* Old, char* New)
1216 //user_hash::iterator newnick;
1217 user_hash::iterator oldnick = clientlist.find(Old);
1219 log(DEBUG,"ReHashNick: %s %s",Old,New);
1221 if (!strcasecmp(Old,New))
1223 log(DEBUG,"old nick is new nick, skipping");
1224 return oldnick->second;
1227 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1229 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1231 userrec* olduser = oldnick->second;
1232 clientlist[New] = olduser;
1233 clientlist.erase(oldnick);
1235 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1237 return clientlist[New];
1240 /* adds or updates an entry in the whowas list */
1241 void AddWhoWas(userrec* u)
1243 whowas_hash::iterator iter = whowas.find(u->nick);
1244 WhoWasUser *a = new WhoWasUser();
1245 strlcpy(a->nick,u->nick,NICKMAX);
1246 strlcpy(a->ident,u->ident,IDENTMAX);
1247 strlcpy(a->dhost,u->dhost,160);
1248 strlcpy(a->host,u->host,160);
1249 strlcpy(a->fullname,u->fullname,MAXGECOS);
1250 strlcpy(a->server,u->server,256);
1251 a->signon = u->signon;
1253 /* MAX_WHOWAS: max number of /WHOWAS items
1254 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1255 * can be replaced by a newer one
1258 if (iter == whowas.end())
1260 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1262 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1264 // 3600 seconds in an hour ;)
1265 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1267 // delete the old one
1268 if (i->second) delete i->second;
1269 // replace with new one
1271 log(DEBUG,"added WHOWAS entry, purged an old record");
1275 // no space left and user doesnt exist. Don't leave ram in use!
1276 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1281 log(DEBUG,"added fresh WHOWAS entry");
1282 whowas[a->nick] = a;
1287 log(DEBUG,"updated WHOWAS entry");
1288 if (iter->second) delete iter->second;
1294 void* dns_task(void* arg)
1296 userrec* u = (userrec*)arg;
1297 log(DEBUG,"DNS thread for user %s",u->nick);
1302 if (dns1.ReverseLookup(u->ip))
1304 log(DEBUG,"DNS Step 1");
1305 while (!dns1.HasResult())
1309 host = dns1.GetResult();
1312 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1313 if (dns2.ForwardLookup(host))
1315 while (!dns2.HasResult())
1319 ip = dns2.GetResultIP();
1320 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1321 if (ip == std::string(u->ip))
1323 log(DEBUG,"DNS Step 4");
1324 if (host.length() < 160)
1326 log(DEBUG,"DNS Step 5");
1327 strcpy(u->host,host.c_str());
1328 strcpy(u->dhost,host.c_str());
1339 /* add a client connection to the sockets list */
1340 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1344 user_hash::iterator iter;
1346 tempnick = ConvToStr(socket) + "-unknown";
1347 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1349 iter = clientlist.find(tempnick);
1352 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1353 // using one as a registered connection. As theyre per fd, we can also safely assume
1354 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1355 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1356 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1357 // issue in earlier alphas/betas
1358 if (iter != clientlist.end())
1360 userrec* goner = iter->second;
1362 clientlist.erase(iter);
1366 * It is OK to access the value here this way since we know
1367 * it exists, we just created it above.
1369 * At NO other time should you access a value in a map or a
1370 * hash_map this way.
1372 clientlist[tempnick] = new userrec();
1374 NonBlocking(socket);
1375 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1377 clientlist[tempnick]->fd = socket;
1378 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1379 strlcpy(clientlist[tempnick]->host, host,160);
1380 strlcpy(clientlist[tempnick]->dhost, host,160);
1381 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1382 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1383 clientlist[tempnick]->registered = 0;
1384 clientlist[tempnick]->signon = TIME+dns_timeout;
1385 clientlist[tempnick]->lastping = 1;
1386 clientlist[tempnick]->port = port;
1387 strlcpy(clientlist[tempnick]->ip,ip,16);
1389 // set the registration timeout for this user
1390 unsigned long class_regtimeout = 90;
1391 int class_flood = 0;
1392 long class_threshold = 5;
1393 long class_sqmax = 262144; // 256kb
1394 long class_rqmax = 4096; // 4k
1396 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1398 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1400 class_regtimeout = (unsigned long)i->registration_timeout;
1401 class_flood = i->flood;
1402 clientlist[tempnick]->pingmax = i->pingtime;
1403 class_threshold = i->threshold;
1404 class_sqmax = i->sendqmax;
1405 class_rqmax = i->recvqmax;
1410 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1411 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1412 clientlist[tempnick]->flood = class_flood;
1413 clientlist[tempnick]->threshold = class_threshold;
1414 clientlist[tempnick]->sendqmax = class_sqmax;
1415 clientlist[tempnick]->recvqmax = class_rqmax;
1420 for (int i = 0; i < MAXCHANS; i++)
1421 clientlist[tempnick]->chans.push_back(a);
1423 if (clientlist.size() > SoftLimit)
1425 kill_link(clientlist[tempnick],"No more connections allowed");
1429 if (clientlist.size() >= MAXCLIENTS)
1431 kill_link(clientlist[tempnick],"No more connections allowed");
1435 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1436 // its a pretty big but for the moment valid assumption:
1437 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1438 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1439 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1440 // which for the time being is a physical impossibility (even the largest networks dont have more
1441 // than about 10,000 users on ONE server!)
1442 if ((unsigned)socket > 65534)
1444 kill_link(clientlist[tempnick],"Server is full");
1449 char* e = matches_exception(ip);
1452 char* r = matches_zline(ip);
1455 char reason[MAXBUF];
1456 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1457 kill_link(clientlist[tempnick],reason);
1461 fd_ref_table[socket] = clientlist[tempnick];
1462 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1465 /* shows the message of the day, and any other on-logon stuff */
1466 void FullConnectUser(userrec* user)
1469 user->idle_lastmsg = TIME;
1470 log(DEBUG,"ConnectUser: %s",user->nick);
1472 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1474 kill_link(user,"Invalid password");
1479 kill_link(user,"Unauthorised connection");
1483 char match_against[MAXBUF];
1484 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1485 char* e = matches_exception(match_against);
1488 char* r = matches_gline(match_against);
1491 char reason[MAXBUF];
1492 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1493 kill_link_silent(user,reason);
1496 r = matches_kline(user->host);
1499 char reason[MAXBUF];
1500 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1501 kill_link_silent(user,reason);
1507 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1508 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1509 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1510 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1511 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1512 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1513 std::stringstream v;
1514 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1515 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1516 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1518 std::string data005 = v.str();
1519 FOREACH_MOD On005Numeric(data005);
1520 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1521 // so i'd better split it :)
1522 std::stringstream out(data005);
1523 std::string token = "";
1524 std::string line5 = "";
1525 int token_counter = 0;
1529 line5 = line5 + token + " ";
1531 if ((token_counter >= 13) || (out.eof() == true))
1533 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1540 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1541 // onto the network and produce 'fake direction'
1542 FOREACH_MOD OnUserConnect(user);
1543 FOREACH_MOD OnGlobalConnect(user);
1544 user->registered = 7;
1545 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1549 /* shows the message of the day, and any other on-logon stuff */
1550 void ConnectUser(userrec *user)
1552 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1553 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1555 FullConnectUser(user);
1559 std::string GetVersionString()
1561 char Revision[] = "$Revision$";
1562 char versiondata[MAXBUF];
1563 char *s1 = Revision;
1565 char *v2 = strtok_r(s1," ",&savept);
1567 v2 = strtok_r(s1," ",&savept);
1570 char dnsengine[] = "multithread";
1572 char dnsengine[] = "singlethread";
1574 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1578 void handle_version(char **parameters, int pcnt, userrec *user)
1580 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1584 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1586 for (unsigned int i = 0; i < cmdlist.size(); i++)
1588 if (!strcasecmp(cmdlist[i].command,commandname))
1590 if (cmdlist[i].handler_function)
1592 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1594 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1596 if (cmdlist[i].flags_needed)
1598 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1616 // calls a handler function for a command
1618 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1620 for (unsigned int i = 0; i < cmdlist.size(); i++)
1622 if (!strcasecmp(cmdlist[i].command,commandname))
1624 if (cmdlist[i].handler_function)
1626 if (pcnt>=cmdlist[i].min_params)
1628 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1630 if (cmdlist[i].flags_needed)
1632 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1634 cmdlist[i].handler_function(parameters,pcnt,user);
1639 cmdlist[i].handler_function(parameters,pcnt,user);
1649 void force_nickchange(userrec* user,const char* newnick)
1656 FOREACH_RESULT(OnUserPreNick(user,newnick));
1659 kill_link(user,"Nickname collision");
1662 if (matches_qline(newnick))
1665 kill_link(user,"Nickname collision");
1673 strncpy(nick,newnick,MAXBUF);
1675 if (user->registered == 7)
1679 handle_nick(pars,1,user);
1685 int process_parameters(char **command_p,char *parameters)
1688 int q = strlen(parameters);
1691 /* no parameters, command_p invalid! */
1694 if (parameters[0] == ':')
1696 command_p[0] = parameters+1;
1701 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1703 /* only one parameter */
1704 command_p[0] = parameters;
1705 if (parameters[0] == ':')
1707 if (strchr(parameters,' ') != NULL)
1715 command_p[j++] = parameters;
1716 for (int i = 0; i <= q; i++)
1718 if (parameters[i] == ' ')
1720 command_p[j++] = parameters+i+1;
1721 parameters[i] = '\0';
1722 if (command_p[j-1][0] == ':')
1724 *command_p[j-1]++; /* remove dodgy ":" */
1726 /* parameter like this marks end of the sequence */
1730 return j; /* returns total number of items in the list */
1733 void process_command(userrec *user, char* cmd)
1737 char *command_p[127];
1738 char p[MAXBUF], temp[MAXBUF];
1739 int j, items, cmd_found;
1741 for (int i = 0; i < 127; i++)
1742 command_p[i] = NULL;
1757 int total_params = 0;
1760 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1762 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1765 // found a 'trailing', we dont count them after this.
1773 // another phidjit bug...
1774 if (total_params > 126)
1776 *(strchr(cmd,' ')) = '\0';
1777 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1781 strlcpy(temp,cmd,MAXBUF);
1783 std::string tmp = cmd;
1784 for (int i = 0; i <= MODCOUNT; i++)
1786 std::string oldtmp = tmp;
1787 modules[i]->OnServerRaw(tmp,true,user);
1790 log(DEBUG,"A Module changed the input string!");
1791 log(DEBUG,"New string: %s",tmp.c_str());
1792 log(DEBUG,"Old string: %s",oldtmp.c_str());
1796 strlcpy(cmd,tmp.c_str(),MAXBUF);
1797 strlcpy(temp,cmd,MAXBUF);
1799 if (!strchr(cmd,' '))
1801 /* no parameters, lets skip the formalities and not chop up
1803 log(DEBUG,"About to preprocess command with no params");
1805 command_p[0] = NULL;
1807 for (unsigned int i = 0; i <= strlen(cmd); i++)
1809 cmd[i] = toupper(cmd[i]);
1817 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1818 for (unsigned int i = 0; i < strlen(temp); i++)
1820 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1826 /* split the full string into a command plus parameters */
1830 if (strchr(cmd,' '))
1832 for (unsigned int i = 0; i <= strlen(cmd); i++)
1834 /* capitalise the command ONLY, leave params intact */
1835 cmd[i] = toupper(cmd[i]);
1836 /* are we nearly there yet?! :P */
1840 parameters = cmd+i+1;
1848 for (unsigned int i = 0; i <= strlen(cmd); i++)
1850 cmd[i] = toupper(cmd[i]);
1857 if (strlen(command)>MAXCOMMAND)
1859 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1863 for (unsigned int x = 0; x < strlen(command); x++)
1865 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1867 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1869 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1872 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1879 for (unsigned int i = 0; i != cmdlist.size(); i++)
1881 if (cmdlist[i].command[0])
1883 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1889 items = process_parameters(command_p,parameters);
1894 command_p[0] = NULL;
1900 command_p[0] = NULL;
1905 /* activity resets the ping pending timer */
1906 user->nping = TIME + user->pingmax;
1907 if ((items) < cmdlist[i].min_params)
1909 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1910 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1913 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1915 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1916 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1920 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1922 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1923 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1927 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1929 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1931 if ((!isnick(user->nick)) || (user->registered != 7))
1933 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1934 WriteServ(user->fd,"451 %s :You have not registered",command);
1938 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1940 std::stringstream dcmds(DisabledCommands);
1941 while (!dcmds.eof())
1943 std::string thiscmd;
1945 if (!strcasecmp(thiscmd.c_str(),command))
1947 // command is disabled!
1948 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1953 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1955 if (cmdlist[i].handler_function)
1958 /* ikky /stats counters */
1961 cmdlist[i].use_count++;
1962 cmdlist[i].total_bytes+=strlen(temp);
1966 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1967 if (MOD_RESULT == 1) {
1971 /* WARNING: nothing may come after the
1972 * command handler call, as the handler
1973 * may free the user structure! */
1975 cmdlist[i].handler_function(command_p,items,user);
1981 WriteServ(user->fd,"451 %s :You have not registered",command);
1989 if ((!cmd_found) && (user))
1992 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1996 bool removecommands(const char* source)
1998 bool go_again = true;
2002 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2004 if (!strcmp(i->source,source))
2006 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2017 void process_buffer(const char* cmdbuf,userrec *user)
2021 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2027 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2034 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2036 strlcpy(cmd,cmdbuf,MAXBUF);
2041 int sl = strlen(cmd)-1;
2042 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2047 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2052 while (cmd[sl] == ' ') // strip trailing spaces
2062 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2064 if ((user) && (cmd))
2066 process_command(user,cmd);
2070 char MODERR[MAXBUF];
2077 void erase_factory(int j)
2080 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2085 factory.push_back(NULL);
2092 void erase_module(int j)
2095 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2101 modules.push_back(NULL);
2107 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2111 module_names.erase(v);
2119 bool UnloadModule(const char* filename)
2121 std::string filename_str = filename;
2122 for (unsigned int j = 0; j != module_names.size(); j++)
2124 if (module_names[j] == filename_str)
2126 if (modules[j]->GetVersion().Flags & VF_STATIC)
2128 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2129 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2132 /* Give the module a chance to tidy out all its metadata */
2133 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2135 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2137 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2139 modules[j]->OnCleanup(TYPE_USER,u->second);
2141 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2143 log(DEBUG,"Deleting module...");
2145 log(DEBUG,"Erasing module entry...");
2147 log(DEBUG,"Removing dependent commands...");
2148 removecommands(filename);
2149 log(DEFAULT,"Module %s unloaded",filename);
2154 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2155 snprintf(MODERR,MAXBUF,"Module not loaded");
2159 bool LoadModule(const char* filename)
2161 char modfile[MAXBUF];
2163 snprintf(modfile,MAXBUF,"%s",filename);
2165 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2167 std::string filename_str = filename;
2169 if (!DirValid(modfile))
2171 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2172 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2176 log(DEBUG,"Loading module: %s",modfile);
2178 if (FileExists(modfile))
2181 for (unsigned int j = 0; j < module_names.size(); j++)
2183 if (module_names[j] == filename_str)
2185 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2186 snprintf(MODERR,MAXBUF,"Module already loaded");
2190 ircd_module* a = new ircd_module(modfile);
2191 factory[MODCOUNT+1] = a;
2192 if (factory[MODCOUNT+1]->LastError())
2194 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2195 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2199 if (factory[MODCOUNT+1]->factory)
2201 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2202 modules[MODCOUNT+1] = m;
2203 /* save the module and the module's classfactory, if
2204 * this isnt done, random crashes can occur :/ */
2205 module_names.push_back(filename);
2209 log(DEFAULT,"Unable to load %s",modfile);
2210 snprintf(MODERR,MAXBUF,"Factory function failed!");
2217 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2218 snprintf(MODERR,MAXBUF,"Module file could not be found");
2223 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2229 int clientportcount = 0;
2230 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2232 ConfValue("bind","port",count,configToken,&config_f);
2233 ConfValue("bind","address",count,Addr,&config_f);
2234 ConfValue("bind","type",count,Type,&config_f);
2235 if (strcmp(Type,"servers"))
2237 // modules handle server bind types now,
2238 // its not a typo in the strcmp.
2239 ports[clientportcount] = atoi(configToken);
2240 strlcpy(addrs[clientportcount],Addr,256);
2242 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2245 portCount = clientportcount;
2247 for (int count = 0; count < portCount; count++)
2249 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2251 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2254 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2256 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2258 else /* well we at least bound to one socket so we'll continue */
2264 /* if we didn't bind to anything then abort */
2265 if (!boundPortCount)
2267 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2268 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2272 return boundPortCount;
2275 int InspIRCd(char** argv, int argc)
2277 bool expire_run = false;
2278 std::vector<int> activefds;
2282 InspSocket* s = NULL;
2283 InspSocket* s_del = NULL;
2285 unsigned int numberactive;
2286 sockaddr_in sock_us; // our port number
2287 socklen_t uslen; // length of our port number
2289 /* Beta 7 moved all this stuff out of the main function
2290 * into smaller sub-functions, much tidier -- Brain
2292 OpenLog(argv, argc);
2294 SetupCommandTable();
2295 ReadConfig(true,NULL);
2296 AddServerName(ServerName);
2298 boundPortCount = BindPorts();
2301 startup_time = time(NULL);
2304 ConfValue("pid","file",0,PID,&config_f);
2305 // write once here, to try it out and make sure its ok
2310 if (DaemonSeed() == ERROR)
2312 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2317 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2318 * initialize the socket engine.
2320 SE = new SocketEngine();
2322 /* We must load the modules AFTER initializing the socket engine, now */
2325 printf("\nInspIRCd is now running!\n");
2328 freopen("/dev/null","w",stdout);
2329 freopen("/dev/null","w",stderr);
2332 /* Add the listening sockets used for client inbound connections
2333 * to the socket engine
2335 for (int count = 0; count < portCount; count++)
2336 SE->AddFd(openSockfd[count],true,X_LISTEN);
2340 /* main loop, this never returns */
2343 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2344 * Once per loop iteration is pleanty.
2349 /* Run background module timers every few seconds
2350 * (the docs say modules shouldnt rely on accurate
2351 * timing using this event, so we dont have to
2352 * time this exactly).
2354 if (((TIME % 8) == 0) && (!expire_run))
2357 FOREACH_MOD OnBackgroundTimer(TIME);
2361 if ((TIME % 8) == 1)
2364 /* Once a second, do the background processing */
2365 if (TIME != OLDTIME)
2366 while (DoBackgroundUserStuff(TIME));
2368 /* Call the socket engine to wait on the active
2369 * file descriptors. The socket engine has everything's
2370 * descriptors in its list... dns, modules, users,
2371 * servers... so its nice and easy, just one call.
2373 SE->Wait(activefds);
2376 * Now process each of the fd's. For users, we have a fast
2377 * lookup table which can find a user by file descriptor, so
2378 * processing them by fd isnt expensive. If we have a lot of
2379 * listening ports or module sockets though, things could get
2382 numberactive = activefds.size();
2383 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2385 int socket_type = SE->GetType(activefds[activefd]);
2386 switch (socket_type)
2388 case X_ESTAB_CLIENT:
2390 cu = fd_ref_table[activefds[activefd]];
2396 case X_ESTAB_MODULE:
2398 /* Process module-owned sockets.
2399 * Modules are encouraged to inherit their sockets from
2400 * InspSocket so we can process them neatly like this.
2402 s = socket_ref[activefds[activefd]];
2404 if ((s) && (!s->Poll()))
2406 log(DEBUG,"Socket poll returned false, close and bail");
2407 SE->DelFd(s->GetFd());
2408 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2410 s_del = (InspSocket*)*a;
2411 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2413 module_sockets.erase(a);
2425 /* When we are using single-threaded dns,
2426 * the sockets for dns end up in our mainloop.
2427 * When we are using multi-threaded dns,
2428 * each thread has its own basic poll() loop
2429 * within it, making them 'fire and forget'
2430 * and independent of the mainloop.
2432 #ifndef THREADED_DNS
2433 dns_poll(activefds[activefd]);
2439 /* It's a listener */
2440 uslen = sizeof(sock_us);
2441 length = sizeof(client);
2442 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2443 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2445 in_port = ntohs(sock_us.sin_port);
2446 log(DEBUG,"Accepted socket %d",incomingSockfd);
2447 target = (char*)inet_ntoa(client.sin_addr);
2448 /* Years and years ago, we used to resolve here
2449 * using gethostbyaddr(). That is sucky and we
2450 * don't do that any more...
2452 if (incomingSockfd >= 0)
2454 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2456 AddClient(incomingSockfd, target, in_port, false, target);
2457 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2461 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2462 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2468 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2469 shutdown(incomingSockfd,2);
2470 close(incomingSockfd);
2475 /* Something went wrong if we're in here.
2476 * In fact, so wrong, im not quite sure
2477 * what we would do, so for now, its going
2478 * to safely do bugger all.
2485 /* This is never reached -- we hope! */