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));
599 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
604 log(DEBUG,"add_channel: no key given in JOIN");
605 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
610 if (strcasecmp(key,Ptr->key))
612 log(DEBUG,"add_channel: bad key given in JOIN");
613 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
619 if (Ptr->binarymodes & CM_INVITEONLY)
622 FOREACH_RESULT(OnCheckInvite(user, Ptr));
625 log(DEBUG,"add_channel: channel is +i");
626 if (user->IsInvited(Ptr->name))
628 /* user was invited to channel */
629 /* there may be an optional channel NOTICE here */
633 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
637 user->RemoveInvite(Ptr->name);
642 FOREACH_RESULT(OnCheckLimit(user, Ptr));
645 if (usercount(Ptr) >= Ptr->limit)
647 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
652 if (Ptr->bans.size())
654 log(DEBUG,"add_channel: about to walk banlist");
656 FOREACH_RESULT(OnCheckBan(user, Ptr));
659 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
661 if (match(user->GetFullHost(),i->data))
663 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
673 log(DEBUG,"Overridden checks");
678 log(DEBUG,"Passed channel checks");
680 for (unsigned int index =0; index < user->chans.size(); index++)
682 if (user->chans[index].channel == NULL)
684 return ForceChan(Ptr,user->chans[index],user,created);
687 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
688 * and put the channel in here. Same for remote users which are not bound by
689 * the channel limits. Otherwise, nope, youre boned.
694 chanrec* c = ForceChan(Ptr,a,user,created);
695 user->chans.push_back(a);
698 else if (strchr(user->modes,'o'))
700 /* Oper allows extension up to the OPERMAXCHANS value */
701 if (user->chans.size() < OPERMAXCHANS)
704 chanrec* c = ForceChan(Ptr,a,user,created);
705 user->chans.push_back(a);
709 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
710 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
714 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
718 /* first user in is given ops */
719 a.uc_modes = UCMODE_OP;
726 Ptr->AddUser((char*)user);
727 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
728 log(DEBUG,"Sent JOIN to client");
731 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
732 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
735 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
736 FOREACH_MOD OnUserJoin(user,Ptr);
740 /* remove a channel from a users record, and remove the record from memory
741 * if the channel has become empty */
743 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
745 if ((!user) || (!cname))
747 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
751 chanrec* Ptr = FindChan(cname);
756 FOREACH_MOD OnUserPart(user,Ptr);
757 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
759 for (unsigned int i =0; i < user->chans.size(); i++)
761 /* zap it from the channel list of the user */
762 if (user->chans[i].channel == Ptr)
766 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
770 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
772 user->chans[i].uc_modes = 0;
773 user->chans[i].channel = NULL;
774 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
779 Ptr->DelUser((char*)user);
781 /* if there are no users left on the channel */
784 chan_hash::iterator iter = chanlist.find(Ptr->name);
786 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
788 /* kill the record */
789 if (iter != chanlist.end())
791 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
793 chanlist.erase(iter);
801 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
803 if ((!src) || (!user) || (!Ptr) || (!reason))
805 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
809 if ((!Ptr) || (!user) || (!src))
814 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
816 if (!has_channel(user,Ptr))
818 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
823 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
824 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
827 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
829 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
831 if (cstatus(src,Ptr) == STATUS_HOP)
833 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
837 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
844 if (!is_uline(src->server))
847 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
852 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
854 for (unsigned int i =0; i < user->chans.size(); i++)
856 /* zap it from the channel list of the user */
857 if (user->chans[i].channel)
858 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
860 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
861 user->chans[i].uc_modes = 0;
862 user->chans[i].channel = NULL;
863 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
868 Ptr->DelUser((char*)user);
870 /* if there are no users left on the channel */
873 chan_hash::iterator iter = chanlist.find(Ptr->name);
875 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
877 /* kill the record */
878 if (iter != chanlist.end())
880 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
882 chanlist.erase(iter);
890 /* This function pokes and hacks at a parameter list like the following:
892 * PART #winbot,#darkgalaxy :m00!
894 * to turn it into a series of individual calls like this:
897 * PART #darkgalaxy :m00!
899 * The seperate calls are sent to a callback function provided by the caller
900 * (the caller will usually call itself recursively). The callback function
901 * must be a command handler. Calling this function on a line with no list causes
902 * no action to be taken. You must provide a starting and ending parameter number
903 * where the range of the list can be found, useful if you have a terminating
904 * parameter as above which is actually not part of the list, or parameters
905 * before the actual list as well. This code is used by many functions which
906 * can function as "one to list" (see the RFC) */
908 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
913 char blog[32][MAXBUF];
914 char blog2[32][MAXBUF];
915 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
919 for (int i = 0; i <32; i++)
922 for (int i = 0; i <32; i++)
926 for (int i = 0; i <10; i++)
935 if (pcnt > 1) /* we have a key to copy */
937 strlcpy(keystr,parameters[1],MAXBUF);
941 if (!parameters[start])
945 if (!strchr(parameters[start],','))
950 for (int i = start; i <= end; i++)
954 strlcat(plist,parameters[i],MAXBUF);
962 for (int i = 0; i < t; i++)
967 strlcpy(blog[j++],param,MAXBUF);
971 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
976 strlcpy(blog[j++],param,MAXBUF);
979 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
984 if ((joins) && (keystr))
986 if (strchr(keystr,','))
991 for (int i = 0; i < t2; i++)
993 if (keystr[i] == ',')
996 strlcpy(blog2[j++],param,MAXBUF);
1000 strlcpy(blog2[j++],param,MAXBUF);
1005 for (j = 0; j < total; j++)
1011 for (q = end; q < pcnt-1; q++)
1013 if (parameters[q+1])
1015 pars[q-end+1] = parameters[q+1];
1018 if ((joins) && (parameters[1]))
1029 /* repeatedly call the function with the hacked parameter list */
1030 if ((joins) && (pcnt > 1))
1034 // pars[1] already set up and containing key from blog2[j]
1039 pars[1] = parameters[1];
1045 fn(pars,pcnt-(end-start),u);
1054 void kill_link(userrec *user,const char* r)
1056 user_hash::iterator iter = clientlist.find(user->nick);
1058 char reason[MAXBUF];
1060 strncpy(reason,r,MAXBUF);
1062 if (strlen(reason)>MAXQUIT)
1064 reason[MAXQUIT-1] = '\0';
1067 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1068 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1069 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1071 if (user->registered == 7) {
1072 FOREACH_MOD OnUserQuit(user,reason);
1073 WriteCommonExcept(user,"QUIT :%s",reason);
1076 user->FlushWriteBuf();
1078 FOREACH_MOD OnUserDisconnect(user);
1082 FOREACH_MOD OnRawSocketClose(user->fd);
1083 SE->DelFd(user->fd);
1084 user->CloseSocket();
1087 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1088 // if they were an oper with +s.
1089 if (user->registered == 7) {
1090 purge_empty_chans(user);
1091 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1093 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1097 if (iter != clientlist.end())
1099 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1101 fd_ref_table[user->fd] = NULL;
1102 clientlist.erase(iter);
1107 void kill_link_silent(userrec *user,const char* r)
1109 user_hash::iterator iter = clientlist.find(user->nick);
1111 char reason[MAXBUF];
1113 strncpy(reason,r,MAXBUF);
1115 if (strlen(reason)>MAXQUIT)
1117 reason[MAXQUIT-1] = '\0';
1120 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1121 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1122 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1124 user->FlushWriteBuf();
1126 if (user->registered == 7) {
1127 FOREACH_MOD OnUserQuit(user,reason);
1128 WriteCommonExcept(user,"QUIT :%s",reason);
1131 FOREACH_MOD OnUserDisconnect(user);
1135 FOREACH_MOD OnRawSocketClose(user->fd);
1136 SE->DelFd(user->fd);
1137 user->CloseSocket();
1140 if (user->registered == 7) {
1141 purge_empty_chans(user);
1144 if (iter != clientlist.end())
1146 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1148 fd_ref_table[user->fd] = NULL;
1149 clientlist.erase(iter);
1155 int main(int argc, char** argv)
1159 log(DEBUG,"*** InspIRCd starting up!");
1160 if (!FileExists(CONFIG_FILE))
1162 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1163 log(DEFAULT,"main: no config");
1164 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1168 for (int i = 1; i < argc; i++)
1170 if (!strcmp(argv[i],"-nofork")) {
1173 if (!strcmp(argv[i],"-wait")) {
1176 if (!strcmp(argv[i],"-nolimit")) {
1182 strlcpy(MyExecutable,argv[0],MAXBUF);
1184 // initialize the lowercase mapping table
1185 for (unsigned int cn = 0; cn < 256; cn++)
1187 // lowercase the uppercase chars
1188 for (unsigned int cn = 65; cn < 91; cn++)
1189 lowermap[cn] = tolower(cn);
1190 // now replace the specific chars for scandanavian comparison
1191 lowermap[(unsigned)'['] = '{';
1192 lowermap[(unsigned)']'] = '}';
1193 lowermap[(unsigned)'\\'] = '|';
1195 if (InspIRCd(argv,argc) == ERROR)
1197 log(DEFAULT,"main: daemon function bailed");
1198 printf("ERROR: could not initialise. Shutting down.\n");
1205 template<typename T> inline string ConvToStr(const T &in)
1208 if (!(tmp << in)) return string();
1212 /* re-allocates a nick in the user_hash after they change nicknames,
1213 * returns a pointer to the new user as it may have moved */
1215 userrec* ReHashNick(char* Old, char* New)
1217 //user_hash::iterator newnick;
1218 user_hash::iterator oldnick = clientlist.find(Old);
1220 log(DEBUG,"ReHashNick: %s %s",Old,New);
1222 if (!strcasecmp(Old,New))
1224 log(DEBUG,"old nick is new nick, skipping");
1225 return oldnick->second;
1228 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1230 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1232 userrec* olduser = oldnick->second;
1233 clientlist[New] = olduser;
1234 clientlist.erase(oldnick);
1236 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1238 return clientlist[New];
1241 /* adds or updates an entry in the whowas list */
1242 void AddWhoWas(userrec* u)
1244 whowas_hash::iterator iter = whowas.find(u->nick);
1245 WhoWasUser *a = new WhoWasUser();
1246 strlcpy(a->nick,u->nick,NICKMAX);
1247 strlcpy(a->ident,u->ident,IDENTMAX);
1248 strlcpy(a->dhost,u->dhost,160);
1249 strlcpy(a->host,u->host,160);
1250 strlcpy(a->fullname,u->fullname,MAXGECOS);
1251 strlcpy(a->server,u->server,256);
1252 a->signon = u->signon;
1254 /* MAX_WHOWAS: max number of /WHOWAS items
1255 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1256 * can be replaced by a newer one
1259 if (iter == whowas.end())
1261 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1263 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1265 // 3600 seconds in an hour ;)
1266 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1268 // delete the old one
1269 if (i->second) delete i->second;
1270 // replace with new one
1272 log(DEBUG,"added WHOWAS entry, purged an old record");
1276 // no space left and user doesnt exist. Don't leave ram in use!
1277 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1282 log(DEBUG,"added fresh WHOWAS entry");
1283 whowas[a->nick] = a;
1288 log(DEBUG,"updated WHOWAS entry");
1289 if (iter->second) delete iter->second;
1295 void* dns_task(void* arg)
1297 userrec* u = (userrec*)arg;
1298 log(DEBUG,"DNS thread for user %s",u->nick);
1303 if (dns1.ReverseLookup(u->ip))
1305 log(DEBUG,"DNS Step 1");
1306 while (!dns1.HasResult())
1310 host = dns1.GetResult();
1313 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1314 if (dns2.ForwardLookup(host))
1316 while (!dns2.HasResult())
1320 ip = dns2.GetResultIP();
1321 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1322 if (ip == std::string(u->ip))
1324 log(DEBUG,"DNS Step 4");
1325 if (host.length() < 160)
1327 log(DEBUG,"DNS Step 5");
1328 strcpy(u->host,host.c_str());
1329 strcpy(u->dhost,host.c_str());
1340 /* add a client connection to the sockets list */
1341 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1345 user_hash::iterator iter;
1347 tempnick = ConvToStr(socket) + "-unknown";
1348 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1350 iter = clientlist.find(tempnick);
1353 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1354 // using one as a registered connection. As theyre per fd, we can also safely assume
1355 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1356 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1357 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1358 // issue in earlier alphas/betas
1359 if (iter != clientlist.end())
1361 userrec* goner = iter->second;
1363 clientlist.erase(iter);
1367 * It is OK to access the value here this way since we know
1368 * it exists, we just created it above.
1370 * At NO other time should you access a value in a map or a
1371 * hash_map this way.
1373 clientlist[tempnick] = new userrec();
1375 NonBlocking(socket);
1376 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1378 clientlist[tempnick]->fd = socket;
1379 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1380 strlcpy(clientlist[tempnick]->host, host,160);
1381 strlcpy(clientlist[tempnick]->dhost, host,160);
1382 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1383 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1384 clientlist[tempnick]->registered = 0;
1385 clientlist[tempnick]->signon = TIME+dns_timeout;
1386 clientlist[tempnick]->lastping = 1;
1387 clientlist[tempnick]->port = port;
1388 strlcpy(clientlist[tempnick]->ip,ip,16);
1390 // set the registration timeout for this user
1391 unsigned long class_regtimeout = 90;
1392 int class_flood = 0;
1393 long class_threshold = 5;
1394 long class_sqmax = 262144; // 256kb
1395 long class_rqmax = 4096; // 4k
1397 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1399 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1401 class_regtimeout = (unsigned long)i->registration_timeout;
1402 class_flood = i->flood;
1403 clientlist[tempnick]->pingmax = i->pingtime;
1404 class_threshold = i->threshold;
1405 class_sqmax = i->sendqmax;
1406 class_rqmax = i->recvqmax;
1411 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1412 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1413 clientlist[tempnick]->flood = class_flood;
1414 clientlist[tempnick]->threshold = class_threshold;
1415 clientlist[tempnick]->sendqmax = class_sqmax;
1416 clientlist[tempnick]->recvqmax = class_rqmax;
1421 for (int i = 0; i < MAXCHANS; i++)
1422 clientlist[tempnick]->chans.push_back(a);
1424 if (clientlist.size() > SoftLimit)
1426 kill_link(clientlist[tempnick],"No more connections allowed");
1430 if (clientlist.size() >= MAXCLIENTS)
1432 kill_link(clientlist[tempnick],"No more connections allowed");
1436 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1437 // its a pretty big but for the moment valid assumption:
1438 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1439 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1440 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1441 // which for the time being is a physical impossibility (even the largest networks dont have more
1442 // than about 10,000 users on ONE server!)
1443 if ((unsigned)socket > 65534)
1445 kill_link(clientlist[tempnick],"Server is full");
1450 char* e = matches_exception(ip);
1453 char* r = matches_zline(ip);
1456 char reason[MAXBUF];
1457 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1458 kill_link(clientlist[tempnick],reason);
1462 fd_ref_table[socket] = clientlist[tempnick];
1463 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1466 /* shows the message of the day, and any other on-logon stuff */
1467 void FullConnectUser(userrec* user)
1470 user->idle_lastmsg = TIME;
1471 log(DEBUG,"ConnectUser: %s",user->nick);
1473 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1475 kill_link(user,"Invalid password");
1480 kill_link(user,"Unauthorised connection");
1484 char match_against[MAXBUF];
1485 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1486 char* e = matches_exception(match_against);
1489 char* r = matches_gline(match_against);
1492 char reason[MAXBUF];
1493 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1494 kill_link_silent(user,reason);
1497 r = matches_kline(user->host);
1500 char reason[MAXBUF];
1501 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1502 kill_link_silent(user,reason);
1508 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1509 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1510 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1511 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1512 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1513 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1514 std::stringstream v;
1515 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1516 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1517 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1519 std::string data005 = v.str();
1520 FOREACH_MOD On005Numeric(data005);
1521 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1522 // so i'd better split it :)
1523 std::stringstream out(data005);
1524 std::string token = "";
1525 std::string line5 = "";
1526 int token_counter = 0;
1530 line5 = line5 + token + " ";
1532 if ((token_counter >= 13) || (out.eof() == true))
1534 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1541 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1542 // onto the network and produce 'fake direction'
1543 FOREACH_MOD OnUserConnect(user);
1544 FOREACH_MOD OnGlobalConnect(user);
1545 user->registered = 7;
1546 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1550 /* shows the message of the day, and any other on-logon stuff */
1551 void ConnectUser(userrec *user)
1553 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1554 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1556 FullConnectUser(user);
1560 std::string GetVersionString()
1562 char Revision[] = "$Revision$";
1563 char versiondata[MAXBUF];
1564 char *s1 = Revision;
1566 char *v2 = strtok_r(s1," ",&savept);
1568 v2 = strtok_r(s1," ",&savept);
1571 char dnsengine[] = "multithread";
1573 char dnsengine[] = "singlethread";
1575 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1579 void handle_version(char **parameters, int pcnt, userrec *user)
1581 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1585 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1587 for (unsigned int i = 0; i < cmdlist.size(); i++)
1589 if (!strcasecmp(cmdlist[i].command,commandname))
1591 if (cmdlist[i].handler_function)
1593 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1595 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1597 if (cmdlist[i].flags_needed)
1599 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1617 // calls a handler function for a command
1619 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1621 for (unsigned int i = 0; i < cmdlist.size(); i++)
1623 if (!strcasecmp(cmdlist[i].command,commandname))
1625 if (cmdlist[i].handler_function)
1627 if (pcnt>=cmdlist[i].min_params)
1629 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1631 if (cmdlist[i].flags_needed)
1633 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1635 cmdlist[i].handler_function(parameters,pcnt,user);
1640 cmdlist[i].handler_function(parameters,pcnt,user);
1650 void force_nickchange(userrec* user,const char* newnick)
1657 FOREACH_RESULT(OnUserPreNick(user,newnick));
1660 kill_link(user,"Nickname collision");
1663 if (matches_qline(newnick))
1666 kill_link(user,"Nickname collision");
1674 strncpy(nick,newnick,MAXBUF);
1676 if (user->registered == 7)
1680 handle_nick(pars,1,user);
1686 int process_parameters(char **command_p,char *parameters)
1689 int q = strlen(parameters);
1692 /* no parameters, command_p invalid! */
1695 if (parameters[0] == ':')
1697 command_p[0] = parameters+1;
1702 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1704 /* only one parameter */
1705 command_p[0] = parameters;
1706 if (parameters[0] == ':')
1708 if (strchr(parameters,' ') != NULL)
1716 command_p[j++] = parameters;
1717 for (int i = 0; i <= q; i++)
1719 if (parameters[i] == ' ')
1721 command_p[j++] = parameters+i+1;
1722 parameters[i] = '\0';
1723 if (command_p[j-1][0] == ':')
1725 *command_p[j-1]++; /* remove dodgy ":" */
1727 /* parameter like this marks end of the sequence */
1731 return j; /* returns total number of items in the list */
1734 void process_command(userrec *user, char* cmd)
1738 char *command_p[127];
1739 char p[MAXBUF], temp[MAXBUF];
1740 int j, items, cmd_found;
1742 for (int i = 0; i < 127; i++)
1743 command_p[i] = NULL;
1758 int total_params = 0;
1761 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1763 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1766 // found a 'trailing', we dont count them after this.
1774 // another phidjit bug...
1775 if (total_params > 126)
1777 *(strchr(cmd,' ')) = '\0';
1778 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1782 strlcpy(temp,cmd,MAXBUF);
1784 std::string tmp = cmd;
1785 for (int i = 0; i <= MODCOUNT; i++)
1787 std::string oldtmp = tmp;
1788 modules[i]->OnServerRaw(tmp,true,user);
1791 log(DEBUG,"A Module changed the input string!");
1792 log(DEBUG,"New string: %s",tmp.c_str());
1793 log(DEBUG,"Old string: %s",oldtmp.c_str());
1797 strlcpy(cmd,tmp.c_str(),MAXBUF);
1798 strlcpy(temp,cmd,MAXBUF);
1800 if (!strchr(cmd,' '))
1802 /* no parameters, lets skip the formalities and not chop up
1804 log(DEBUG,"About to preprocess command with no params");
1806 command_p[0] = NULL;
1808 for (unsigned int i = 0; i <= strlen(cmd); i++)
1810 cmd[i] = toupper(cmd[i]);
1818 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1819 for (unsigned int i = 0; i < strlen(temp); i++)
1821 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1827 /* split the full string into a command plus parameters */
1831 if (strchr(cmd,' '))
1833 for (unsigned int i = 0; i <= strlen(cmd); i++)
1835 /* capitalise the command ONLY, leave params intact */
1836 cmd[i] = toupper(cmd[i]);
1837 /* are we nearly there yet?! :P */
1841 parameters = cmd+i+1;
1849 for (unsigned int i = 0; i <= strlen(cmd); i++)
1851 cmd[i] = toupper(cmd[i]);
1858 if (strlen(command)>MAXCOMMAND)
1860 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1864 for (unsigned int x = 0; x < strlen(command); x++)
1866 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1868 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1870 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1873 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1880 for (unsigned int i = 0; i != cmdlist.size(); i++)
1882 if (cmdlist[i].command[0])
1884 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1890 items = process_parameters(command_p,parameters);
1895 command_p[0] = NULL;
1901 command_p[0] = NULL;
1906 /* activity resets the ping pending timer */
1907 user->nping = TIME + user->pingmax;
1908 if ((items) < cmdlist[i].min_params)
1910 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1911 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1914 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1916 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1917 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1921 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1923 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1924 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1928 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1930 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1932 if ((!isnick(user->nick)) || (user->registered != 7))
1934 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1935 WriteServ(user->fd,"451 %s :You have not registered",command);
1939 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1941 std::stringstream dcmds(DisabledCommands);
1942 while (!dcmds.eof())
1944 std::string thiscmd;
1946 if (!strcasecmp(thiscmd.c_str(),command))
1948 // command is disabled!
1949 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1954 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1956 if (cmdlist[i].handler_function)
1959 /* ikky /stats counters */
1962 cmdlist[i].use_count++;
1963 cmdlist[i].total_bytes+=strlen(temp);
1967 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1968 if (MOD_RESULT == 1) {
1972 /* WARNING: nothing may come after the
1973 * command handler call, as the handler
1974 * may free the user structure! */
1976 cmdlist[i].handler_function(command_p,items,user);
1982 WriteServ(user->fd,"451 %s :You have not registered",command);
1990 if ((!cmd_found) && (user))
1993 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1997 bool removecommands(const char* source)
1999 bool go_again = true;
2003 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2005 if (!strcmp(i->source,source))
2007 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2018 void process_buffer(const char* cmdbuf,userrec *user)
2022 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2028 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2035 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2037 strlcpy(cmd,cmdbuf,MAXBUF);
2042 int sl = strlen(cmd)-1;
2043 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2048 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2053 while (cmd[sl] == ' ') // strip trailing spaces
2063 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2065 if ((user) && (cmd))
2067 process_command(user,cmd);
2071 char MODERR[MAXBUF];
2078 void erase_factory(int j)
2081 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2086 factory.push_back(NULL);
2093 void erase_module(int j)
2096 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2102 modules.push_back(NULL);
2108 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2112 module_names.erase(v);
2120 bool UnloadModule(const char* filename)
2122 std::string filename_str = filename;
2123 for (unsigned int j = 0; j != module_names.size(); j++)
2125 if (module_names[j] == filename_str)
2127 if (modules[j]->GetVersion().Flags & VF_STATIC)
2129 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2130 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2133 /* Give the module a chance to tidy out all its metadata */
2134 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2136 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2138 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2140 modules[j]->OnCleanup(TYPE_USER,u->second);
2142 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2144 log(DEBUG,"Deleting module...");
2146 log(DEBUG,"Erasing module entry...");
2148 log(DEBUG,"Removing dependent commands...");
2149 removecommands(filename);
2150 log(DEFAULT,"Module %s unloaded",filename);
2155 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2156 snprintf(MODERR,MAXBUF,"Module not loaded");
2160 bool LoadModule(const char* filename)
2162 char modfile[MAXBUF];
2164 snprintf(modfile,MAXBUF,"%s",filename);
2166 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2168 std::string filename_str = filename;
2170 if (!DirValid(modfile))
2172 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2173 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2177 log(DEBUG,"Loading module: %s",modfile);
2179 if (FileExists(modfile))
2182 for (unsigned int j = 0; j < module_names.size(); j++)
2184 if (module_names[j] == filename_str)
2186 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2187 snprintf(MODERR,MAXBUF,"Module already loaded");
2191 ircd_module* a = new ircd_module(modfile);
2192 factory[MODCOUNT+1] = a;
2193 if (factory[MODCOUNT+1]->LastError())
2195 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2196 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2200 if (factory[MODCOUNT+1]->factory)
2202 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2203 modules[MODCOUNT+1] = m;
2204 /* save the module and the module's classfactory, if
2205 * this isnt done, random crashes can occur :/ */
2206 module_names.push_back(filename);
2210 log(DEFAULT,"Unable to load %s",modfile);
2211 snprintf(MODERR,MAXBUF,"Factory function failed!");
2218 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2219 snprintf(MODERR,MAXBUF,"Module file could not be found");
2224 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2230 int clientportcount = 0;
2231 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2233 ConfValue("bind","port",count,configToken,&config_f);
2234 ConfValue("bind","address",count,Addr,&config_f);
2235 ConfValue("bind","type",count,Type,&config_f);
2236 if (strcmp(Type,"servers"))
2238 // modules handle server bind types now,
2239 // its not a typo in the strcmp.
2240 ports[clientportcount] = atoi(configToken);
2241 strlcpy(addrs[clientportcount],Addr,256);
2243 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2246 portCount = clientportcount;
2248 for (int count = 0; count < portCount; count++)
2250 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2252 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2255 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2257 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2259 else /* well we at least bound to one socket so we'll continue */
2265 /* if we didn't bind to anything then abort */
2266 if (!boundPortCount)
2268 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2269 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2273 return boundPortCount;
2276 int InspIRCd(char** argv, int argc)
2278 bool expire_run = false;
2279 std::vector<int> activefds;
2283 InspSocket* s = NULL;
2284 InspSocket* s_del = NULL;
2286 unsigned int numberactive;
2287 sockaddr_in sock_us; // our port number
2288 socklen_t uslen; // length of our port number
2290 /* Beta 7 moved all this stuff out of the main function
2291 * into smaller sub-functions, much tidier -- Brain
2293 OpenLog(argv, argc);
2295 SetupCommandTable();
2296 ReadConfig(true,NULL);
2297 AddServerName(ServerName);
2299 boundPortCount = BindPorts();
2302 startup_time = time(NULL);
2305 ConfValue("pid","file",0,PID,&config_f);
2306 // write once here, to try it out and make sure its ok
2311 if (DaemonSeed() == ERROR)
2313 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2318 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2319 * initialize the socket engine.
2321 SE = new SocketEngine();
2323 /* We must load the modules AFTER initializing the socket engine, now */
2326 printf("\nInspIRCd is now running!\n");
2329 freopen("/dev/null","w",stdout);
2330 freopen("/dev/null","w",stderr);
2333 /* Add the listening sockets used for client inbound connections
2334 * to the socket engine
2336 for (int count = 0; count < portCount; count++)
2337 SE->AddFd(openSockfd[count],true,X_LISTEN);
2341 /* main loop, this never returns */
2344 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2345 * Once per loop iteration is pleanty.
2350 /* Run background module timers every few seconds
2351 * (the docs say modules shouldnt rely on accurate
2352 * timing using this event, so we dont have to
2353 * time this exactly).
2355 if (((TIME % 8) == 0) && (!expire_run))
2358 FOREACH_MOD OnBackgroundTimer(TIME);
2362 if ((TIME % 8) == 1)
2365 /* Once a second, do the background processing */
2366 if (TIME != OLDTIME)
2367 while (DoBackgroundUserStuff(TIME));
2369 /* Call the socket engine to wait on the active
2370 * file descriptors. The socket engine has everything's
2371 * descriptors in its list... dns, modules, users,
2372 * servers... so its nice and easy, just one call.
2374 SE->Wait(activefds);
2377 * Now process each of the fd's. For users, we have a fast
2378 * lookup table which can find a user by file descriptor, so
2379 * processing them by fd isnt expensive. If we have a lot of
2380 * listening ports or module sockets though, things could get
2383 numberactive = activefds.size();
2384 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2386 int socket_type = SE->GetType(activefds[activefd]);
2387 switch (socket_type)
2389 case X_ESTAB_CLIENT:
2391 cu = fd_ref_table[activefds[activefd]];
2397 case X_ESTAB_MODULE:
2399 /* Process module-owned sockets.
2400 * Modules are encouraged to inherit their sockets from
2401 * InspSocket so we can process them neatly like this.
2403 s = socket_ref[activefds[activefd]];
2405 if ((s) && (!s->Poll()))
2407 log(DEBUG,"Socket poll returned false, close and bail");
2408 SE->DelFd(s->GetFd());
2409 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2411 s_del = (InspSocket*)*a;
2412 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2414 module_sockets.erase(a);
2426 /* When we are using single-threaded dns,
2427 * the sockets for dns end up in our mainloop.
2428 * When we are using multi-threaded dns,
2429 * each thread has its own basic poll() loop
2430 * within it, making them 'fire and forget'
2431 * and independent of the mainloop.
2433 #ifndef THREADED_DNS
2434 dns_poll(activefds[activefd]);
2440 /* It's a listener */
2441 uslen = sizeof(sock_us);
2442 length = sizeof(client);
2443 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2444 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2446 in_port = ntohs(sock_us.sin_port);
2447 log(DEBUG,"Accepted socket %d",incomingSockfd);
2448 target = (char*)inet_ntoa(client.sin_addr);
2449 /* Years and years ago, we used to resolve here
2450 * using gethostbyaddr(). That is sucky and we
2451 * don't do that any more...
2453 if (incomingSockfd >= 0)
2455 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2457 AddClient(incomingSockfd, target, in_port, false, target);
2458 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2462 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2463 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2469 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2470 shutdown(incomingSockfd,2);
2471 close(incomingSockfd);
2476 /* Something went wrong if we're in here.
2477 * In fact, so wrong, im not quite sure
2478 * what we would do, so for now, its going
2479 * to safely do bugger all.
2486 /* This is never reached -- we hope! */