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"
65 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
66 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
68 time_t startup_time = time(NULL);
70 extern std::vector<Module*> modules;
71 std::vector<std::string> module_names;
72 extern std::vector<ircd_module*> factory;
74 std::vector<InspSocket*> module_sockets;
77 int openSockfd[MAXSOCKS];
78 struct sockaddr_in client,server;
81 extern InspSocket* socket_ref[65535];
83 time_t TIME = time(NULL), OLDTIME = time(NULL);
85 SocketEngine* SE = NULL;
87 extern std::vector<std::string> include_stack;
89 // This table references users by file descriptor.
90 // its an array to make it VERY fast, as all lookups are referenced
91 // by an integer, meaning there is no need for a scan/search operation.
92 userrec* fd_ref_table[65536];
94 serverstats* stats = new serverstats;
95 Server* MyServer = new Server;
96 ServerConfig *Config = new ServerConfig;
101 command_table cmdlist;
107 servernamelist servernames;
109 int boundPortCount = 0;
110 int portCount = 0, ports[MAXSOCKS];
114 int has_channel(userrec *u, chanrec *c);
115 int usercount(chanrec *c);
116 int usercount_i(chanrec *c);
117 char* Passwd(userrec *user);
118 bool IsDenied(userrec *user);
119 void AddWhoWas(userrec* u);
121 std::stringstream config_f(stringstream::in | stringstream::out);
123 std::vector<userrec*> all_opers;
127 void AddOper(userrec* user)
129 log(DEBUG,"Oper added to optimization list");
130 all_opers.push_back(user);
133 void AddServerName(std::string servername)
135 log(DEBUG,"Adding server name: %s",servername.c_str());
136 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
138 if (*a == servername)
141 servernames.push_back(servername);
144 const char* FindServerNamePtr(std::string servername)
146 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
148 if (*a == servername)
151 AddServerName(servername);
152 return FindServerNamePtr(servername);
155 void DeleteOper(userrec* user)
157 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
161 log(DEBUG,"Oper removed from optimization list");
168 std::string GetRevision()
170 /* w00t got me to replace a bunch of strtok_r
171 * with something nicer, so i did this. Its the
172 * same thing really, only in C++. It places the
173 * text into a std::stringstream which is a readable
174 * and writeable buffer stream, and then pops two
175 * words off it, space delimited. Because it reads
176 * into the same variable twice, the first word
177 * is discarded, and the second one returned.
179 std::stringstream Revision("$Revision$");
181 Revision >> single >> single;
186 std::string getservername()
188 return Config->ServerName;
191 std::string getserverdesc()
193 return Config->ServerDesc;
196 std::string getnetworkname()
198 return Config->Network;
201 std::string getadminname()
203 return Config->AdminName;
206 std::string getadminemail()
208 return Config->AdminEmail;
211 std::string getadminnick()
213 return Config->AdminNick;
216 void ReadConfig(bool bail, userrec* user)
218 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
219 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
221 std::stringstream errstr;
222 include_stack.clear();
224 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
227 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
230 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
238 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
239 while (!errstr.eof())
241 errstr.getline(dataline,1024);
242 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
247 WriteOpers("There were errors in the configuration file:");
248 while (!errstr.eof())
250 errstr.getline(dataline,1024);
251 WriteOpers(dataline);
258 ConfValue("server","name",0,Config->ServerName,&config_f);
259 ConfValue("server","description",0,Config->ServerDesc,&config_f);
260 ConfValue("server","network",0,Config->Network,&config_f);
261 ConfValue("admin","name",0,Config->AdminName,&config_f);
262 ConfValue("admin","email",0,Config->AdminEmail,&config_f);
263 ConfValue("admin","nick",0,Config->AdminNick,&config_f);
264 ConfValue("files","motd",0,Config->motd,&config_f);
265 ConfValue("files","rules",0,Config->rules,&config_f);
266 ConfValue("power","diepass",0,Config->diepass,&config_f);
267 ConfValue("power","pause",0,pauseval,&config_f);
268 ConfValue("power","restartpass",0,Config->restartpass,&config_f);
269 ConfValue("options","prefixquit",0,Config->PrefixQuit,&config_f);
270 ConfValue("die","value",0,Config->DieValue,&config_f);
271 ConfValue("options","loglevel",0,dbg,&config_f);
272 ConfValue("options","netbuffersize",0,NB,&config_f);
273 ConfValue("options","maxwho",0,MW,&config_f);
274 ConfValue("options","allowhalfop",0,AH,&config_f);
275 ConfValue("options","allowprotect",0,AP,&config_f);
276 ConfValue("options","allowfounder",0,AF,&config_f);
277 ConfValue("dns","server",0,Config->DNSServer,&config_f);
278 ConfValue("dns","timeout",0,DNT,&config_f);
279 ConfValue("options","moduledir",0,Config->ModPath,&config_f);
280 ConfValue("disabled","commands",0,Config->DisabledCommands,&config_f);
281 ConfValue("options","somaxconn",0,MCON,&config_f);
282 ConfValue("options","softlimit",0,SLIMT,&config_f);
284 Config->SoftLimit = atoi(SLIMT);
285 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
287 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
288 Config->SoftLimit = MAXCLIENTS;
290 Config->MaxConn = atoi(MCON);
291 if (Config->MaxConn > SOMAXCONN)
292 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
293 Config->NetBufferSize = atoi(NB);
294 Config->MaxWhoResults = atoi(MW);
295 Config->dns_timeout = atoi(DNT);
296 if (!Config->dns_timeout)
297 Config->dns_timeout = 5;
298 if (!Config->MaxConn)
299 Config->MaxConn = SOMAXCONN;
300 if (!*Config->DNSServer)
301 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
302 if (!*Config->ModPath)
303 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
304 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
305 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
307 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
308 Config->NetBufferSize = 10240;
310 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
312 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
313 Config->MaxWhoResults = 128;
315 Config->LogLevel = DEFAULT;
316 if (!strcmp(dbg,"debug"))
318 Config->LogLevel = DEBUG;
319 Config->debugging = 1;
321 if (!strcmp(dbg,"verbose"))
322 Config->LogLevel = VERBOSE;
323 if (!strcmp(dbg,"default"))
324 Config->LogLevel = DEFAULT;
325 if (!strcmp(dbg,"sparse"))
326 Config->LogLevel = SPARSE;
327 if (!strcmp(dbg,"none"))
328 Config->LogLevel = NONE;
330 readfile(MOTD,Config->motd);
331 log(DEFAULT,"Reading message of the day...");
332 readfile(RULES,Config->rules);
333 log(DEFAULT,"Reading connect classes...");
335 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
338 ConfValue("connect","allow",i,Value,&config_f);
339 ConfValue("connect","timeout",i,timeout,&config_f);
340 ConfValue("connect","flood",i,flood,&config_f);
341 ConfValue("connect","pingfreq",i,pfreq,&config_f);
342 ConfValue("connect","threshold",i,thold,&config_f);
343 ConfValue("connect","sendq",i,sqmax,&config_f);
344 ConfValue("connect","recvq",i,rqmax,&config_f);
347 strlcpy(c.host,Value,MAXBUF);
349 strlcpy(Value,"",MAXBUF);
350 ConfValue("connect","password",i,Value,&config_f);
351 strlcpy(c.pass,Value,MAXBUF);
352 c.registration_timeout = 90; // default is 2 minutes
354 c.flood = atoi(flood);
356 c.sendqmax = 262144; // 256k
357 c.recvqmax = 4096; // 4k
360 c.threshold = atoi(thold);
364 c.sendqmax = atoi(sqmax);
368 c.recvqmax = atoi(rqmax);
372 c.registration_timeout = atoi(timeout);
376 c.pingtime = atoi(pfreq);
378 Classes.push_back(c);
379 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);
383 ConfValue("connect","deny",i,Value,&config_f);
384 strlcpy(c.host,Value,MAXBUF);
386 Classes.push_back(c);
387 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
391 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
392 read_xline_defaults();
393 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
394 apply_lines(APPLY_ALL);
396 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
399 log(DEFAULT,"Adding and removing modules due to rehash...");
401 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
403 // store the old module names
404 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
406 old_module_names.push_back(*t);
409 // get the new module names
410 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
412 ConfValue("module","name",count2,Value,&config_f);
413 new_module_names.push_back(Value);
416 // now create a list of new modules that are due to be loaded
417 // and a seperate list of modules which are due to be unloaded
418 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
421 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
427 added_modules.push_back(*_new);
429 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
432 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
438 removed_modules.push_back(*oldm);
440 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
442 int rem = 0, add = 0;
443 if (!removed_modules.empty())
444 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
446 if (UnloadModule(removing->c_str()))
448 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
449 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
454 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
457 if (!added_modules.empty())
458 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
460 if (LoadModule(adding->c_str()))
462 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
463 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
468 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
471 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());
476 /* add a channel to a user, creating the record for it if needed and linking
477 * it to the user record */
479 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
481 if ((!user) || (!cn))
483 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
490 strncpy(cname,cn,CHANMAX);
492 log(DEBUG,"add_channel: %s %s",user->nick,cname);
494 chanrec* Ptr = FindChan(cname);
501 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
505 /* create a new one */
506 chanlist[cname] = new chanrec();
507 strlcpy(chanlist[cname]->name, cname,CHANMAX);
508 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
509 chanlist[cname]->created = TIME;
510 strcpy(chanlist[cname]->topic, "");
511 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
512 chanlist[cname]->topicset = 0;
513 Ptr = chanlist[cname];
514 log(DEBUG,"add_channel: created: %s",cname);
515 /* set created to 2 to indicate user
516 * is the first in the channel
517 * and should be given ops */
522 /* Already on the channel */
523 if (has_channel(user,Ptr))
526 // remote users are allowed us to bypass channel modes
527 // and bans (used by servers)
531 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
541 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
546 log(DEBUG,"add_channel: no key given in JOIN");
547 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
552 if (strcasecmp(key,Ptr->key))
554 log(DEBUG,"add_channel: bad key given in JOIN");
555 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
561 if (Ptr->binarymodes & CM_INVITEONLY)
564 FOREACH_RESULT(OnCheckInvite(user, Ptr));
567 log(DEBUG,"add_channel: channel is +i");
568 if (user->IsInvited(Ptr->name))
570 /* user was invited to channel */
571 /* there may be an optional channel NOTICE here */
575 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
579 user->RemoveInvite(Ptr->name);
584 FOREACH_RESULT(OnCheckLimit(user, Ptr));
587 if (usercount(Ptr) >= Ptr->limit)
589 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
594 if (Ptr->bans.size())
596 log(DEBUG,"add_channel: about to walk banlist");
598 FOREACH_RESULT(OnCheckBan(user, Ptr));
601 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
603 if (match(user->GetFullHost(),i->data))
605 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
615 log(DEBUG,"Overridden checks");
620 log(DEBUG,"Passed channel checks");
622 for (unsigned int index =0; index < user->chans.size(); index++)
624 if (user->chans[index].channel == NULL)
626 return ForceChan(Ptr,user->chans[index],user,created);
629 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
630 * and put the channel in here. Same for remote users which are not bound by
631 * the channel limits. Otherwise, nope, youre boned.
636 chanrec* c = ForceChan(Ptr,a,user,created);
637 user->chans.push_back(a);
640 else if (strchr(user->modes,'o'))
642 /* Oper allows extension up to the OPERMAXCHANS value */
643 if (user->chans.size() < OPERMAXCHANS)
646 chanrec* c = ForceChan(Ptr,a,user,created);
647 user->chans.push_back(a);
651 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
652 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
656 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
660 /* first user in is given ops */
661 a.uc_modes = UCMODE_OP;
668 Ptr->AddUser((char*)user);
669 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
670 log(DEBUG,"Sent JOIN to client");
673 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
674 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
677 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
678 FOREACH_MOD OnUserJoin(user,Ptr);
682 /* remove a channel from a users record, and remove the record from memory
683 * if the channel has become empty */
685 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
687 if ((!user) || (!cname))
689 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
693 chanrec* Ptr = FindChan(cname);
698 FOREACH_MOD OnUserPart(user,Ptr);
699 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
701 for (unsigned int i =0; i < user->chans.size(); i++)
703 /* zap it from the channel list of the user */
704 if (user->chans[i].channel == Ptr)
708 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
712 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
714 user->chans[i].uc_modes = 0;
715 user->chans[i].channel = NULL;
716 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
721 Ptr->DelUser((char*)user);
723 /* if there are no users left on the channel */
726 chan_hash::iterator iter = chanlist.find(Ptr->name);
728 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
730 /* kill the record */
731 if (iter != chanlist.end())
733 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
735 chanlist.erase(iter);
743 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
745 if ((!src) || (!user) || (!Ptr) || (!reason))
747 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
751 if ((!Ptr) || (!user) || (!src))
756 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
758 if (!has_channel(user,Ptr))
760 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
765 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
766 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
769 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
771 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
773 if (cstatus(src,Ptr) == STATUS_HOP)
775 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
779 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
786 if (!is_uline(src->server))
789 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
794 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
796 for (unsigned int i =0; i < user->chans.size(); i++)
798 /* zap it from the channel list of the user */
799 if (user->chans[i].channel)
800 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
802 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
803 user->chans[i].uc_modes = 0;
804 user->chans[i].channel = NULL;
805 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
810 Ptr->DelUser((char*)user);
812 /* if there are no users left on the channel */
815 chan_hash::iterator iter = chanlist.find(Ptr->name);
817 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
819 /* kill the record */
820 if (iter != chanlist.end())
822 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
824 chanlist.erase(iter);
832 /* This function pokes and hacks at a parameter list like the following:
834 * PART #winbot,#darkgalaxy :m00!
836 * to turn it into a series of individual calls like this:
839 * PART #darkgalaxy :m00!
841 * The seperate calls are sent to a callback function provided by the caller
842 * (the caller will usually call itself recursively). The callback function
843 * must be a command handler. Calling this function on a line with no list causes
844 * no action to be taken. You must provide a starting and ending parameter number
845 * where the range of the list can be found, useful if you have a terminating
846 * parameter as above which is actually not part of the list, or parameters
847 * before the actual list as well. This code is used by many functions which
848 * can function as "one to list" (see the RFC) */
850 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
855 char blog[32][MAXBUF];
856 char blog2[32][MAXBUF];
857 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
861 for (int i = 0; i <32; i++)
864 for (int i = 0; i <32; i++)
868 for (int i = 0; i <10; i++)
877 if (pcnt > 1) /* we have a key to copy */
879 strlcpy(keystr,parameters[1],MAXBUF);
883 if (!parameters[start])
887 if (!strchr(parameters[start],','))
892 for (int i = start; i <= end; i++)
896 strlcat(plist,parameters[i],MAXBUF);
904 for (int i = 0; i < t; i++)
909 strlcpy(blog[j++],param,MAXBUF);
913 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
918 strlcpy(blog[j++],param,MAXBUF);
921 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
926 if ((joins) && (keystr))
928 if (strchr(keystr,','))
933 for (int i = 0; i < t2; i++)
935 if (keystr[i] == ',')
938 strlcpy(blog2[j++],param,MAXBUF);
942 strlcpy(blog2[j++],param,MAXBUF);
947 for (j = 0; j < total; j++)
953 for (q = end; q < pcnt-1; q++)
957 pars[q-end+1] = parameters[q+1];
960 if ((joins) && (parameters[1]))
971 /* repeatedly call the function with the hacked parameter list */
972 if ((joins) && (pcnt > 1))
976 // pars[1] already set up and containing key from blog2[j]
981 pars[1] = parameters[1];
987 fn(pars,pcnt-(end-start),u);
996 void kill_link(userrec *user,const char* r)
998 user_hash::iterator iter = clientlist.find(user->nick);
1000 char reason[MAXBUF];
1002 strncpy(reason,r,MAXBUF);
1004 if (strlen(reason)>MAXQUIT)
1006 reason[MAXQUIT-1] = '\0';
1009 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1010 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1011 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1013 if (user->registered == 7) {
1014 FOREACH_MOD OnUserQuit(user,reason);
1015 WriteCommonExcept(user,"QUIT :%s",reason);
1018 user->FlushWriteBuf();
1020 FOREACH_MOD OnUserDisconnect(user);
1024 FOREACH_MOD OnRawSocketClose(user->fd);
1025 SE->DelFd(user->fd);
1026 user->CloseSocket();
1029 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1030 // if they were an oper with +s.
1031 if (user->registered == 7) {
1032 purge_empty_chans(user);
1033 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1035 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1039 if (iter != clientlist.end())
1041 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1043 fd_ref_table[user->fd] = NULL;
1044 clientlist.erase(iter);
1049 void kill_link_silent(userrec *user,const char* r)
1051 user_hash::iterator iter = clientlist.find(user->nick);
1053 char reason[MAXBUF];
1055 strncpy(reason,r,MAXBUF);
1057 if (strlen(reason)>MAXQUIT)
1059 reason[MAXQUIT-1] = '\0';
1062 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1063 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1064 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1066 user->FlushWriteBuf();
1068 if (user->registered == 7) {
1069 FOREACH_MOD OnUserQuit(user,reason);
1070 WriteCommonExcept(user,"QUIT :%s",reason);
1073 FOREACH_MOD OnUserDisconnect(user);
1077 FOREACH_MOD OnRawSocketClose(user->fd);
1078 SE->DelFd(user->fd);
1079 user->CloseSocket();
1082 if (user->registered == 7) {
1083 purge_empty_chans(user);
1086 if (iter != clientlist.end())
1088 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1090 fd_ref_table[user->fd] = NULL;
1091 clientlist.erase(iter);
1097 int main(int argc, char** argv)
1101 log(DEBUG,"*** InspIRCd starting up!");
1102 if (!FileExists(CONFIG_FILE))
1104 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1105 log(DEFAULT,"main: no config");
1106 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1110 for (int i = 1; i < argc; i++)
1112 if (!strcmp(argv[i],"-nofork")) {
1113 Config->nofork = true;
1115 if (!strcmp(argv[i],"-wait")) {
1118 if (!strcmp(argv[i],"-nolimit")) {
1119 Config->unlimitcore = true;
1124 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
1126 // initialize the lowercase mapping table
1127 for (unsigned int cn = 0; cn < 256; cn++)
1129 // lowercase the uppercase chars
1130 for (unsigned int cn = 65; cn < 91; cn++)
1131 lowermap[cn] = tolower(cn);
1132 // now replace the specific chars for scandanavian comparison
1133 lowermap[(unsigned)'['] = '{';
1134 lowermap[(unsigned)']'] = '}';
1135 lowermap[(unsigned)'\\'] = '|';
1137 if (InspIRCd(argv,argc) == ERROR)
1139 log(DEFAULT,"main: daemon function bailed");
1140 printf("ERROR: could not initialise. Shutting down.\n");
1147 template<typename T> inline string ConvToStr(const T &in)
1150 if (!(tmp << in)) return string();
1154 /* re-allocates a nick in the user_hash after they change nicknames,
1155 * returns a pointer to the new user as it may have moved */
1157 userrec* ReHashNick(char* Old, char* New)
1159 //user_hash::iterator newnick;
1160 user_hash::iterator oldnick = clientlist.find(Old);
1162 log(DEBUG,"ReHashNick: %s %s",Old,New);
1164 if (!strcasecmp(Old,New))
1166 log(DEBUG,"old nick is new nick, skipping");
1167 return oldnick->second;
1170 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1172 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1174 userrec* olduser = oldnick->second;
1175 clientlist[New] = olduser;
1176 clientlist.erase(oldnick);
1178 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1180 return clientlist[New];
1183 /* adds or updates an entry in the whowas list */
1184 void AddWhoWas(userrec* u)
1186 whowas_hash::iterator iter = whowas.find(u->nick);
1187 WhoWasUser *a = new WhoWasUser();
1188 strlcpy(a->nick,u->nick,NICKMAX);
1189 strlcpy(a->ident,u->ident,IDENTMAX);
1190 strlcpy(a->dhost,u->dhost,160);
1191 strlcpy(a->host,u->host,160);
1192 strlcpy(a->fullname,u->fullname,MAXGECOS);
1193 strlcpy(a->server,u->server,256);
1194 a->signon = u->signon;
1196 /* MAX_WHOWAS: max number of /WHOWAS items
1197 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1198 * can be replaced by a newer one
1201 if (iter == whowas.end())
1203 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1205 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1207 // 3600 seconds in an hour ;)
1208 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1210 // delete the old one
1211 if (i->second) delete i->second;
1212 // replace with new one
1214 log(DEBUG,"added WHOWAS entry, purged an old record");
1218 // no space left and user doesnt exist. Don't leave ram in use!
1219 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1224 log(DEBUG,"added fresh WHOWAS entry");
1225 whowas[a->nick] = a;
1230 log(DEBUG,"updated WHOWAS entry");
1231 if (iter->second) delete iter->second;
1237 void* dns_task(void* arg)
1239 userrec* u = (userrec*)arg;
1240 log(DEBUG,"DNS thread for user %s",u->nick);
1245 if (dns1.ReverseLookup(u->ip))
1247 log(DEBUG,"DNS Step 1");
1248 while (!dns1.HasResult())
1252 host = dns1.GetResult();
1255 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1256 if (dns2.ForwardLookup(host))
1258 while (!dns2.HasResult())
1262 ip = dns2.GetResultIP();
1263 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1264 if (ip == std::string(u->ip))
1266 log(DEBUG,"DNS Step 4");
1267 if (host.length() < 160)
1269 log(DEBUG,"DNS Step 5");
1270 strcpy(u->host,host.c_str());
1271 strcpy(u->dhost,host.c_str());
1282 /* add a client connection to the sockets list */
1283 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1287 user_hash::iterator iter;
1289 tempnick = ConvToStr(socket) + "-unknown";
1290 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1292 iter = clientlist.find(tempnick);
1295 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1296 // using one as a registered connection. As theyre per fd, we can also safely assume
1297 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1298 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1299 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1300 // issue in earlier alphas/betas
1301 if (iter != clientlist.end())
1303 userrec* goner = iter->second;
1305 clientlist.erase(iter);
1309 * It is OK to access the value here this way since we know
1310 * it exists, we just created it above.
1312 * At NO other time should you access a value in a map or a
1313 * hash_map this way.
1315 clientlist[tempnick] = new userrec();
1317 NonBlocking(socket);
1318 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1320 clientlist[tempnick]->fd = socket;
1321 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1322 strlcpy(clientlist[tempnick]->host, host,160);
1323 strlcpy(clientlist[tempnick]->dhost, host,160);
1324 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
1325 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1326 clientlist[tempnick]->registered = 0;
1327 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
1328 clientlist[tempnick]->lastping = 1;
1329 clientlist[tempnick]->port = port;
1330 strlcpy(clientlist[tempnick]->ip,ip,16);
1332 // set the registration timeout for this user
1333 unsigned long class_regtimeout = 90;
1334 int class_flood = 0;
1335 long class_threshold = 5;
1336 long class_sqmax = 262144; // 256kb
1337 long class_rqmax = 4096; // 4k
1339 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1341 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1343 class_regtimeout = (unsigned long)i->registration_timeout;
1344 class_flood = i->flood;
1345 clientlist[tempnick]->pingmax = i->pingtime;
1346 class_threshold = i->threshold;
1347 class_sqmax = i->sendqmax;
1348 class_rqmax = i->recvqmax;
1353 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
1354 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1355 clientlist[tempnick]->flood = class_flood;
1356 clientlist[tempnick]->threshold = class_threshold;
1357 clientlist[tempnick]->sendqmax = class_sqmax;
1358 clientlist[tempnick]->recvqmax = class_rqmax;
1363 for (int i = 0; i < MAXCHANS; i++)
1364 clientlist[tempnick]->chans.push_back(a);
1366 if (clientlist.size() > Config->SoftLimit)
1368 kill_link(clientlist[tempnick],"No more connections allowed");
1372 if (clientlist.size() >= MAXCLIENTS)
1374 kill_link(clientlist[tempnick],"No more connections allowed");
1378 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1379 // its a pretty big but for the moment valid assumption:
1380 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1381 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1382 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1383 // which for the time being is a physical impossibility (even the largest networks dont have more
1384 // than about 10,000 users on ONE server!)
1385 if ((unsigned)socket > 65534)
1387 kill_link(clientlist[tempnick],"Server is full");
1392 char* e = matches_exception(ip);
1395 char* r = matches_zline(ip);
1398 char reason[MAXBUF];
1399 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1400 kill_link(clientlist[tempnick],reason);
1404 fd_ref_table[socket] = clientlist[tempnick];
1405 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1408 /* shows the message of the day, and any other on-logon stuff */
1409 void FullConnectUser(userrec* user)
1411 stats->statsConnects++;
1412 user->idle_lastmsg = TIME;
1413 log(DEBUG,"ConnectUser: %s",user->nick);
1415 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1417 kill_link(user,"Invalid password");
1422 kill_link(user,"Unauthorised connection");
1426 char match_against[MAXBUF];
1427 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1428 char* e = matches_exception(match_against);
1431 char* r = matches_gline(match_against);
1434 char reason[MAXBUF];
1435 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1436 kill_link_silent(user,reason);
1439 r = matches_kline(user->host);
1442 char reason[MAXBUF];
1443 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1444 kill_link_silent(user,reason);
1450 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1451 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
1452 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1453 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1454 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
1455 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1456 std::stringstream v;
1457 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1458 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1459 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1460 v << Config->Network;
1461 std::string data005 = v.str();
1462 FOREACH_MOD On005Numeric(data005);
1463 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1464 // so i'd better split it :)
1465 std::stringstream out(data005);
1466 std::string token = "";
1467 std::string line5 = "";
1468 int token_counter = 0;
1472 line5 = line5 + token + " ";
1474 if ((token_counter >= 13) || (out.eof() == true))
1476 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1483 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1484 // onto the network and produce 'fake direction'
1485 FOREACH_MOD OnUserConnect(user);
1486 FOREACH_MOD OnGlobalConnect(user);
1487 user->registered = 7;
1488 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1492 /* shows the message of the day, and any other on-logon stuff */
1493 void ConnectUser(userrec *user)
1495 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1496 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1498 FullConnectUser(user);
1502 std::string GetVersionString()
1504 char versiondata[MAXBUF];
1506 char dnsengine[] = "multithread";
1508 char dnsengine[] = "singlethread";
1510 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1514 void handle_version(char **parameters, int pcnt, userrec *user)
1516 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1520 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1522 for (unsigned int i = 0; i < cmdlist.size(); i++)
1524 if (!strcasecmp(cmdlist[i].command,commandname))
1526 if (cmdlist[i].handler_function)
1528 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1530 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1532 if (cmdlist[i].flags_needed)
1534 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1552 // calls a handler function for a command
1554 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1556 for (unsigned int i = 0; i < cmdlist.size(); i++)
1558 if (!strcasecmp(cmdlist[i].command,commandname))
1560 if (cmdlist[i].handler_function)
1562 if (pcnt>=cmdlist[i].min_params)
1564 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1566 if (cmdlist[i].flags_needed)
1568 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1570 cmdlist[i].handler_function(parameters,pcnt,user);
1575 cmdlist[i].handler_function(parameters,pcnt,user);
1585 void force_nickchange(userrec* user,const char* newnick)
1592 FOREACH_RESULT(OnUserPreNick(user,newnick));
1594 stats->statsCollisions++;
1595 kill_link(user,"Nickname collision");
1598 if (matches_qline(newnick))
1600 stats->statsCollisions++;
1601 kill_link(user,"Nickname collision");
1609 strncpy(nick,newnick,MAXBUF);
1611 if (user->registered == 7)
1615 handle_nick(pars,1,user);
1621 int process_parameters(char **command_p,char *parameters)
1624 int q = strlen(parameters);
1627 /* no parameters, command_p invalid! */
1630 if (parameters[0] == ':')
1632 command_p[0] = parameters+1;
1637 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1639 /* only one parameter */
1640 command_p[0] = parameters;
1641 if (parameters[0] == ':')
1643 if (strchr(parameters,' ') != NULL)
1651 command_p[j++] = parameters;
1652 for (int i = 0; i <= q; i++)
1654 if (parameters[i] == ' ')
1656 command_p[j++] = parameters+i+1;
1657 parameters[i] = '\0';
1658 if (command_p[j-1][0] == ':')
1660 *command_p[j-1]++; /* remove dodgy ":" */
1662 /* parameter like this marks end of the sequence */
1666 return j; /* returns total number of items in the list */
1669 void process_command(userrec *user, char* cmd)
1673 char *command_p[127];
1674 char p[MAXBUF], temp[MAXBUF];
1675 int j, items, cmd_found;
1677 for (int i = 0; i < 127; i++)
1678 command_p[i] = NULL;
1693 int total_params = 0;
1696 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1698 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1701 // found a 'trailing', we dont count them after this.
1709 // another phidjit bug...
1710 if (total_params > 126)
1712 *(strchr(cmd,' ')) = '\0';
1713 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1717 strlcpy(temp,cmd,MAXBUF);
1719 std::string tmp = cmd;
1720 for (int i = 0; i <= MODCOUNT; i++)
1722 std::string oldtmp = tmp;
1723 modules[i]->OnServerRaw(tmp,true,user);
1726 log(DEBUG,"A Module changed the input string!");
1727 log(DEBUG,"New string: %s",tmp.c_str());
1728 log(DEBUG,"Old string: %s",oldtmp.c_str());
1732 strlcpy(cmd,tmp.c_str(),MAXBUF);
1733 strlcpy(temp,cmd,MAXBUF);
1735 if (!strchr(cmd,' '))
1737 /* no parameters, lets skip the formalities and not chop up
1739 log(DEBUG,"About to preprocess command with no params");
1741 command_p[0] = NULL;
1743 for (unsigned int i = 0; i <= strlen(cmd); i++)
1745 cmd[i] = toupper(cmd[i]);
1753 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1754 for (unsigned int i = 0; i < strlen(temp); i++)
1756 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1762 /* split the full string into a command plus parameters */
1766 if (strchr(cmd,' '))
1768 for (unsigned int i = 0; i <= strlen(cmd); i++)
1770 /* capitalise the command ONLY, leave params intact */
1771 cmd[i] = toupper(cmd[i]);
1772 /* are we nearly there yet?! :P */
1776 parameters = cmd+i+1;
1784 for (unsigned int i = 0; i <= strlen(cmd); i++)
1786 cmd[i] = toupper(cmd[i]);
1793 if (strlen(command)>MAXCOMMAND)
1795 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1799 for (unsigned int x = 0; x < strlen(command); x++)
1801 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1803 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1805 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1807 stats->statsUnknown++;
1808 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1815 for (unsigned int i = 0; i != cmdlist.size(); i++)
1817 if (cmdlist[i].command[0])
1819 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1825 items = process_parameters(command_p,parameters);
1830 command_p[0] = NULL;
1836 command_p[0] = NULL;
1841 /* activity resets the ping pending timer */
1842 user->nping = TIME + user->pingmax;
1843 if ((items) < cmdlist[i].min_params)
1845 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1846 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1849 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1851 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1852 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1856 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1858 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1859 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1863 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1865 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1867 if ((!isnick(user->nick)) || (user->registered != 7))
1869 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1870 WriteServ(user->fd,"451 %s :You have not registered",command);
1874 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1876 std::stringstream dcmds(Config->DisabledCommands);
1877 while (!dcmds.eof())
1879 std::string thiscmd;
1881 if (!strcasecmp(thiscmd.c_str(),command))
1883 // command is disabled!
1884 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1889 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1891 if (cmdlist[i].handler_function)
1894 /* ikky /stats counters */
1897 cmdlist[i].use_count++;
1898 cmdlist[i].total_bytes+=strlen(temp);
1902 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1903 if (MOD_RESULT == 1) {
1907 /* WARNING: nothing may come after the
1908 * command handler call, as the handler
1909 * may free the user structure! */
1911 cmdlist[i].handler_function(command_p,items,user);
1917 WriteServ(user->fd,"451 %s :You have not registered",command);
1925 if ((!cmd_found) && (user))
1927 stats->statsUnknown++;
1928 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1932 bool removecommands(const char* source)
1934 bool go_again = true;
1938 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1940 if (!strcmp(i->source,source))
1942 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1953 void process_buffer(const char* cmdbuf,userrec *user)
1957 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1963 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1970 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1972 strlcpy(cmd,cmdbuf,MAXBUF);
1977 int sl = strlen(cmd)-1;
1978 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1983 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1988 while (cmd[sl] == ' ') // strip trailing spaces
1998 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2000 if ((user) && (cmd))
2002 process_command(user,cmd);
2006 char MODERR[MAXBUF];
2013 void erase_factory(int j)
2016 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2021 factory.push_back(NULL);
2028 void erase_module(int j)
2031 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2037 modules.push_back(NULL);
2043 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2047 module_names.erase(v);
2055 bool UnloadModule(const char* filename)
2057 std::string filename_str = filename;
2058 for (unsigned int j = 0; j != module_names.size(); j++)
2060 if (module_names[j] == filename_str)
2062 if (modules[j]->GetVersion().Flags & VF_STATIC)
2064 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2065 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2068 /* Give the module a chance to tidy out all its metadata */
2069 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2071 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2073 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2075 modules[j]->OnCleanup(TYPE_USER,u->second);
2077 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2079 log(DEBUG,"Deleting module...");
2081 log(DEBUG,"Erasing module entry...");
2083 log(DEBUG,"Removing dependent commands...");
2084 removecommands(filename);
2085 log(DEFAULT,"Module %s unloaded",filename);
2090 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2091 snprintf(MODERR,MAXBUF,"Module not loaded");
2095 bool LoadModule(const char* filename)
2097 char modfile[MAXBUF];
2099 snprintf(modfile,MAXBUF,"%s",filename);
2101 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
2103 std::string filename_str = filename;
2105 if (!DirValid(modfile))
2107 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2108 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2112 log(DEBUG,"Loading module: %s",modfile);
2114 if (FileExists(modfile))
2117 for (unsigned int j = 0; j < module_names.size(); j++)
2119 if (module_names[j] == filename_str)
2121 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2122 snprintf(MODERR,MAXBUF,"Module already loaded");
2126 ircd_module* a = new ircd_module(modfile);
2127 factory[MODCOUNT+1] = a;
2128 if (factory[MODCOUNT+1]->LastError())
2130 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2131 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2135 if (factory[MODCOUNT+1]->factory)
2137 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2138 modules[MODCOUNT+1] = m;
2139 /* save the module and the module's classfactory, if
2140 * this isnt done, random crashes can occur :/ */
2141 module_names.push_back(filename);
2145 log(DEFAULT,"Unable to load %s",modfile);
2146 snprintf(MODERR,MAXBUF,"Factory function failed!");
2153 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2154 snprintf(MODERR,MAXBUF,"Module file could not be found");
2159 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2165 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2166 int clientportcount = 0;
2167 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2169 ConfValue("bind","port",count,configToken,&config_f);
2170 ConfValue("bind","address",count,Addr,&config_f);
2171 ConfValue("bind","type",count,Type,&config_f);
2172 if (strcmp(Type,"servers"))
2174 // modules handle server bind types now,
2175 // its not a typo in the strcmp.
2176 ports[clientportcount] = atoi(configToken);
2177 strlcpy(Config->addrs[clientportcount],Addr,256);
2179 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2182 portCount = clientportcount;
2184 for (int count = 0; count < portCount; count++)
2186 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2188 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2191 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],Config->addrs[count]) == ERROR)
2193 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2195 else /* well we at least bound to one socket so we'll continue */
2201 /* if we didn't bind to anything then abort */
2202 if (!boundPortCount)
2204 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2205 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2209 return boundPortCount;
2212 int InspIRCd(char** argv, int argc)
2214 bool expire_run = false;
2215 std::vector<int> activefds;
2219 InspSocket* s = NULL;
2220 InspSocket* s_del = NULL;
2222 unsigned int numberactive;
2223 sockaddr_in sock_us; // our port number
2224 socklen_t uslen; // length of our port number
2226 /* Beta 7 moved all this stuff out of the main function
2227 * into smaller sub-functions, much tidier -- Brain
2229 OpenLog(argv, argc);
2230 ReadConfig(true,NULL);
2232 SetupCommandTable();
2233 AddServerName(Config->ServerName);
2235 boundPortCount = BindPorts();
2238 startup_time = time(NULL);
2241 ConfValue("pid","file",0,PID,&config_f);
2242 // write once here, to try it out and make sure its ok
2245 if (!Config->nofork)
2247 if (DaemonSeed() == ERROR)
2249 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2254 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2255 * initialize the socket engine.
2257 SE = new SocketEngine();
2259 /* We must load the modules AFTER initializing the socket engine, now */
2262 printf("\nInspIRCd is now running!\n");
2263 if (!Config->nofork)
2265 freopen("/dev/null","w",stdout);
2266 freopen("/dev/null","w",stderr);
2269 /* Add the listening sockets used for client inbound connections
2270 * to the socket engine
2272 for (int count = 0; count < portCount; count++)
2273 SE->AddFd(openSockfd[count],true,X_LISTEN);
2277 /* main loop, this never returns */
2280 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2281 * Once per loop iteration is pleanty.
2286 /* Run background module timers every few seconds
2287 * (the docs say modules shouldnt rely on accurate
2288 * timing using this event, so we dont have to
2289 * time this exactly).
2291 if (((TIME % 8) == 0) && (!expire_run))
2294 FOREACH_MOD OnBackgroundTimer(TIME);
2298 if ((TIME % 8) == 1)
2301 /* Once a second, do the background processing */
2302 if (TIME != OLDTIME)
2303 while (DoBackgroundUserStuff(TIME));
2305 /* Call the socket engine to wait on the active
2306 * file descriptors. The socket engine has everything's
2307 * descriptors in its list... dns, modules, users,
2308 * servers... so its nice and easy, just one call.
2310 SE->Wait(activefds);
2313 * Now process each of the fd's. For users, we have a fast
2314 * lookup table which can find a user by file descriptor, so
2315 * processing them by fd isnt expensive. If we have a lot of
2316 * listening ports or module sockets though, things could get
2319 numberactive = activefds.size();
2320 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2322 int socket_type = SE->GetType(activefds[activefd]);
2323 switch (socket_type)
2325 case X_ESTAB_CLIENT:
2327 cu = fd_ref_table[activefds[activefd]];
2333 case X_ESTAB_MODULE:
2335 /* Process module-owned sockets.
2336 * Modules are encouraged to inherit their sockets from
2337 * InspSocket so we can process them neatly like this.
2339 s = socket_ref[activefds[activefd]];
2341 if ((s) && (!s->Poll()))
2343 log(DEBUG,"Socket poll returned false, close and bail");
2344 SE->DelFd(s->GetFd());
2345 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2347 s_del = (InspSocket*)*a;
2348 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2350 module_sockets.erase(a);
2362 /* When we are using single-threaded dns,
2363 * the sockets for dns end up in our mainloop.
2364 * When we are using multi-threaded dns,
2365 * each thread has its own basic poll() loop
2366 * within it, making them 'fire and forget'
2367 * and independent of the mainloop.
2369 #ifndef THREADED_DNS
2370 dns_poll(activefds[activefd]);
2376 /* It's a listener */
2377 uslen = sizeof(sock_us);
2378 length = sizeof(client);
2379 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2380 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2382 in_port = ntohs(sock_us.sin_port);
2383 log(DEBUG,"Accepted socket %d",incomingSockfd);
2384 target = (char*)inet_ntoa(client.sin_addr);
2385 /* Years and years ago, we used to resolve here
2386 * using gethostbyaddr(). That is sucky and we
2387 * don't do that any more...
2389 if (incomingSockfd >= 0)
2391 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2392 stats->statsAccept++;
2393 AddClient(incomingSockfd, target, in_port, false, target);
2394 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2398 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2399 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2400 stats->statsRefused++;
2405 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2406 shutdown(incomingSockfd,2);
2407 close(incomingSockfd);
2412 /* Something went wrong if we're in here.
2413 * In fact, so wrong, im not quite sure
2414 * what we would do, so for now, its going
2415 * to safely do bugger all.
2422 /* This is never reached -- we hope! */