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 WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
65 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
67 time_t startup_time = time(NULL);
69 extern std::vector<Module*> modules;
70 std::vector<std::string> module_names;
71 extern std::vector<ircd_module*> factory;
73 std::vector<InspSocket*> module_sockets;
76 int openSockfd[MAXSOCKS];
77 struct sockaddr_in client,server;
80 extern InspSocket* socket_ref[65535];
82 time_t TIME = time(NULL), OLDTIME = time(NULL);
84 SocketEngine* SE = NULL;
86 extern std::vector<std::string> include_stack;
88 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
89 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
90 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
91 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
92 typedef std::deque<command_t> command_table;
93 typedef std::vector<std::string> servernamelist;
95 // This table references users by file descriptor.
96 // its an array to make it VERY fast, as all lookups are referenced
97 // by an integer, meaning there is no need for a scan/search operation.
98 userrec* fd_ref_table[65536];
100 serverstats* stats = new serverstats;
101 Server* MyServer = new Server;
102 ServerConfig *Config = new ServerConfig;
104 user_hash clientlist;
107 command_table cmdlist;
108 autoconnects autoconns;
114 servernamelist servernames;
116 int boundPortCount = 0;
117 int portCount = 0, ports[MAXSOCKS];
121 int has_channel(userrec *u, chanrec *c);
122 int usercount(chanrec *c);
123 int usercount_i(chanrec *c);
124 char* Passwd(userrec *user);
125 bool IsDenied(userrec *user);
126 void AddWhoWas(userrec* u);
128 std::stringstream config_f(stringstream::in | stringstream::out);
130 std::vector<userrec*> all_opers;
134 void AddOper(userrec* user)
136 log(DEBUG,"Oper added to optimization list");
137 all_opers.push_back(user);
140 void AddServerName(std::string servername)
142 log(DEBUG,"Adding server name: %s",servername.c_str());
143 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
145 if (*a == servername)
148 servernames.push_back(servername);
151 const char* FindServerNamePtr(std::string servername)
153 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
155 if (*a == servername)
158 AddServerName(servername);
159 return FindServerNamePtr(servername);
162 void DeleteOper(userrec* user)
164 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
168 log(DEBUG,"Oper removed from optimization list");
175 std::string GetRevision()
177 /* w00t got me to replace a bunch of strtok_r
178 * with something nicer, so i did this. Its the
179 * same thing really, only in C++. It places the
180 * text into a std::stringstream which is a readable
181 * and writeable buffer stream, and then pops two
182 * words off it, space delimited. Because it reads
183 * into the same variable twice, the first word
184 * is discarded, and the second one returned.
186 std::stringstream Revision("$Revision$");
188 Revision >> single >> single;
193 std::string getservername()
195 return Config->ServerName;
198 std::string getserverdesc()
200 return Config->ServerDesc;
203 std::string getnetworkname()
205 return Config->Network;
208 std::string getadminname()
210 return Config->AdminName;
213 std::string getadminemail()
215 return Config->AdminEmail;
218 std::string getadminnick()
220 return Config->AdminNick;
223 void ReadConfig(bool bail, userrec* user)
225 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
226 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
228 std::stringstream errstr;
229 include_stack.clear();
231 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
234 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
237 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
245 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
246 while (!errstr.eof())
248 errstr.getline(dataline,1024);
249 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
254 WriteOpers("There were errors in the configuration file:");
255 while (!errstr.eof())
257 errstr.getline(dataline,1024);
258 WriteOpers(dataline);
265 ConfValue("server","name",0,Config->ServerName,&config_f);
266 ConfValue("server","description",0,Config->ServerDesc,&config_f);
267 ConfValue("server","network",0,Config->Network,&config_f);
268 ConfValue("admin","name",0,Config->AdminName,&config_f);
269 ConfValue("admin","email",0,Config->AdminEmail,&config_f);
270 ConfValue("admin","nick",0,Config->AdminNick,&config_f);
271 ConfValue("files","motd",0,Config->motd,&config_f);
272 ConfValue("files","rules",0,Config->rules,&config_f);
273 ConfValue("power","diepass",0,Config->diepass,&config_f);
274 ConfValue("power","pause",0,pauseval,&config_f);
275 ConfValue("power","restartpass",0,Config->restartpass,&config_f);
276 ConfValue("options","prefixquit",0,Config->PrefixQuit,&config_f);
277 ConfValue("die","value",0,Config->DieValue,&config_f);
278 ConfValue("options","loglevel",0,dbg,&config_f);
279 ConfValue("options","netbuffersize",0,NB,&config_f);
280 ConfValue("options","maxwho",0,MW,&config_f);
281 ConfValue("options","allowhalfop",0,AH,&config_f);
282 ConfValue("options","allowprotect",0,AP,&config_f);
283 ConfValue("options","allowfounder",0,AF,&config_f);
284 ConfValue("dns","server",0,Config->DNSServer,&config_f);
285 ConfValue("dns","timeout",0,DNT,&config_f);
286 ConfValue("options","moduledir",0,Config->ModPath,&config_f);
287 ConfValue("disabled","commands",0,Config->DisabledCommands,&config_f);
288 ConfValue("options","somaxconn",0,MCON,&config_f);
289 ConfValue("options","softlimit",0,SLIMT,&config_f);
291 Config->SoftLimit = atoi(SLIMT);
292 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
294 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
295 Config->SoftLimit = MAXCLIENTS;
297 Config->MaxConn = atoi(MCON);
298 if (MaxConn > SOMAXCONN)
299 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
300 Config->NetBufferSize = atoi(NB);
301 Config->MaxWhoResults = atoi(MW);
302 Config->dns_timeout = atoi(DNT);
303 if (!Config->dns_timeout)
304 Config->dns_timeout = 5;
305 if (!Config->MaxConn)
306 Config->MaxConn = SOMAXCONN;
307 if (!*Config->DNSServer)
308 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
309 if (!*Config->ModPath)
310 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
311 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
312 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
314 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
315 Config->NetBufferSize = 10240;
317 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
319 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
320 Config->MaxWhoResults = 128;
322 if (!strcmp(dbg,"debug"))
324 Config->LogLevel = DEBUG;
325 Config->debugging = 1;
327 if (!strcmp(dbg,"verbose"))
328 Config->LogLevel = VERBOSE;
329 if (!strcmp(dbg,"default"))
330 Config->LogLevel = DEFAULT;
331 if (!strcmp(dbg,"sparse"))
332 Config->LogLevel = SPARSE;
333 if (!strcmp(dbg,"none"))
334 Config->LogLevel = NONE;
335 readfile(MOTD,Config->motd);
336 log(DEFAULT,"Reading message of the day...");
337 readfile(RULES,Config->rules);
338 log(DEFAULT,"Reading connect classes...");
340 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
343 ConfValue("connect","allow",i,Value,&config_f);
344 ConfValue("connect","timeout",i,timeout,&config_f);
345 ConfValue("connect","flood",i,flood,&config_f);
346 ConfValue("connect","pingfreq",i,pfreq,&config_f);
347 ConfValue("connect","threshold",i,thold,&config_f);
348 ConfValue("connect","sendq",i,sqmax,&config_f);
349 ConfValue("connect","recvq",i,rqmax,&config_f);
352 strlcpy(c.host,Value,MAXBUF);
354 strlcpy(Value,"",MAXBUF);
355 ConfValue("connect","password",i,Value,&config_f);
356 strlcpy(c.pass,Value,MAXBUF);
357 c.registration_timeout = 90; // default is 2 minutes
359 c.flood = atoi(flood);
361 c.sendqmax = 262144; // 256k
362 c.recvqmax = 4096; // 4k
365 c.threshold = atoi(thold);
369 c.sendqmax = atoi(sqmax);
373 c.recvqmax = atoi(rqmax);
377 c.registration_timeout = atoi(timeout);
381 c.pingtime = atoi(pfreq);
383 Classes.push_back(c);
384 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);
388 ConfValue("connect","deny",i,Value,&config_f);
389 strlcpy(c.host,Value,MAXBUF);
391 Classes.push_back(c);
392 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
396 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
397 read_xline_defaults();
398 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
399 apply_lines(APPLY_ALL);
401 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
404 log(DEFAULT,"Adding and removing modules due to rehash...");
406 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
408 // store the old module names
409 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
411 old_module_names.push_back(*t);
414 // get the new module names
415 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
417 ConfValue("module","name",count2,Value,&config_f);
418 new_module_names.push_back(Value);
421 // now create a list of new modules that are due to be loaded
422 // and a seperate list of modules which are due to be unloaded
423 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
426 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
432 added_modules.push_back(*_new);
434 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
437 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
443 removed_modules.push_back(*oldm);
445 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
447 int rem = 0, add = 0;
448 if (!removed_modules.empty())
449 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
451 if (UnloadModule(removing->c_str()))
453 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
454 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
459 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
462 if (!added_modules.empty())
463 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
465 if (LoadModule(adding->c_str()))
467 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
468 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
473 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
476 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());
481 /* add a channel to a user, creating the record for it if needed and linking
482 * it to the user record */
484 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
486 if ((!user) || (!cn))
488 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
495 strncpy(cname,cn,CHANMAX);
497 log(DEBUG,"add_channel: %s %s",user->nick,cname);
499 chanrec* Ptr = FindChan(cname);
506 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
510 /* create a new one */
511 chanlist[cname] = new chanrec();
512 strlcpy(chanlist[cname]->name, cname,CHANMAX);
513 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
514 chanlist[cname]->created = TIME;
515 strcpy(chanlist[cname]->topic, "");
516 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
517 chanlist[cname]->topicset = 0;
518 Ptr = chanlist[cname];
519 log(DEBUG,"add_channel: created: %s",cname);
520 /* set created to 2 to indicate user
521 * is the first in the channel
522 * and should be given ops */
527 /* Already on the channel */
528 if (has_channel(user,Ptr))
531 // remote users are allowed us to bypass channel modes
532 // and bans (used by servers)
536 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
546 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
551 log(DEBUG,"add_channel: no key given in JOIN");
552 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
557 if (strcasecmp(key,Ptr->key))
559 log(DEBUG,"add_channel: bad key given in JOIN");
560 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
566 if (Ptr->binarymodes & CM_INVITEONLY)
569 FOREACH_RESULT(OnCheckInvite(user, Ptr));
572 log(DEBUG,"add_channel: channel is +i");
573 if (user->IsInvited(Ptr->name))
575 /* user was invited to channel */
576 /* there may be an optional channel NOTICE here */
580 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
584 user->RemoveInvite(Ptr->name);
589 FOREACH_RESULT(OnCheckLimit(user, Ptr));
592 if (usercount(Ptr) >= Ptr->limit)
594 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
599 if (Ptr->bans.size())
601 log(DEBUG,"add_channel: about to walk banlist");
603 FOREACH_RESULT(OnCheckBan(user, Ptr));
606 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
608 if (match(user->GetFullHost(),i->data))
610 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
620 log(DEBUG,"Overridden checks");
625 log(DEBUG,"Passed channel checks");
627 for (unsigned int index =0; index < user->chans.size(); index++)
629 if (user->chans[index].channel == NULL)
631 return ForceChan(Ptr,user->chans[index],user,created);
634 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
635 * and put the channel in here. Same for remote users which are not bound by
636 * the channel limits. Otherwise, nope, youre boned.
641 chanrec* c = ForceChan(Ptr,a,user,created);
642 user->chans.push_back(a);
645 else if (strchr(user->modes,'o'))
647 /* Oper allows extension up to the OPERMAXCHANS value */
648 if (user->chans.size() < OPERMAXCHANS)
651 chanrec* c = ForceChan(Ptr,a,user,created);
652 user->chans.push_back(a);
656 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
657 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
661 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
665 /* first user in is given ops */
666 a.uc_modes = UCMODE_OP;
673 Ptr->AddUser((char*)user);
674 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
675 log(DEBUG,"Sent JOIN to client");
678 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
679 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
682 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
683 FOREACH_MOD OnUserJoin(user,Ptr);
687 /* remove a channel from a users record, and remove the record from memory
688 * if the channel has become empty */
690 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
692 if ((!user) || (!cname))
694 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
698 chanrec* Ptr = FindChan(cname);
703 FOREACH_MOD OnUserPart(user,Ptr);
704 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
706 for (unsigned int i =0; i < user->chans.size(); i++)
708 /* zap it from the channel list of the user */
709 if (user->chans[i].channel == Ptr)
713 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
717 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
719 user->chans[i].uc_modes = 0;
720 user->chans[i].channel = NULL;
721 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
726 Ptr->DelUser((char*)user);
728 /* if there are no users left on the channel */
731 chan_hash::iterator iter = chanlist.find(Ptr->name);
733 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
735 /* kill the record */
736 if (iter != chanlist.end())
738 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
740 chanlist.erase(iter);
748 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
750 if ((!src) || (!user) || (!Ptr) || (!reason))
752 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
756 if ((!Ptr) || (!user) || (!src))
761 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
763 if (!has_channel(user,Ptr))
765 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
770 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
771 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
774 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
776 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
778 if (cstatus(src,Ptr) == STATUS_HOP)
780 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
784 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
791 if (!is_uline(src->server))
794 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
799 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
801 for (unsigned int i =0; i < user->chans.size(); i++)
803 /* zap it from the channel list of the user */
804 if (user->chans[i].channel)
805 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
807 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
808 user->chans[i].uc_modes = 0;
809 user->chans[i].channel = NULL;
810 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
815 Ptr->DelUser((char*)user);
817 /* if there are no users left on the channel */
820 chan_hash::iterator iter = chanlist.find(Ptr->name);
822 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
824 /* kill the record */
825 if (iter != chanlist.end())
827 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
829 chanlist.erase(iter);
837 /* This function pokes and hacks at a parameter list like the following:
839 * PART #winbot,#darkgalaxy :m00!
841 * to turn it into a series of individual calls like this:
844 * PART #darkgalaxy :m00!
846 * The seperate calls are sent to a callback function provided by the caller
847 * (the caller will usually call itself recursively). The callback function
848 * must be a command handler. Calling this function on a line with no list causes
849 * no action to be taken. You must provide a starting and ending parameter number
850 * where the range of the list can be found, useful if you have a terminating
851 * parameter as above which is actually not part of the list, or parameters
852 * before the actual list as well. This code is used by many functions which
853 * can function as "one to list" (see the RFC) */
855 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
860 char blog[32][MAXBUF];
861 char blog2[32][MAXBUF];
862 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
866 for (int i = 0; i <32; i++)
869 for (int i = 0; i <32; i++)
873 for (int i = 0; i <10; i++)
882 if (pcnt > 1) /* we have a key to copy */
884 strlcpy(keystr,parameters[1],MAXBUF);
888 if (!parameters[start])
892 if (!strchr(parameters[start],','))
897 for (int i = start; i <= end; i++)
901 strlcat(plist,parameters[i],MAXBUF);
909 for (int i = 0; i < t; i++)
914 strlcpy(blog[j++],param,MAXBUF);
918 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
923 strlcpy(blog[j++],param,MAXBUF);
926 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
931 if ((joins) && (keystr))
933 if (strchr(keystr,','))
938 for (int i = 0; i < t2; i++)
940 if (keystr[i] == ',')
943 strlcpy(blog2[j++],param,MAXBUF);
947 strlcpy(blog2[j++],param,MAXBUF);
952 for (j = 0; j < total; j++)
958 for (q = end; q < pcnt-1; q++)
962 pars[q-end+1] = parameters[q+1];
965 if ((joins) && (parameters[1]))
976 /* repeatedly call the function with the hacked parameter list */
977 if ((joins) && (pcnt > 1))
981 // pars[1] already set up and containing key from blog2[j]
986 pars[1] = parameters[1];
992 fn(pars,pcnt-(end-start),u);
1001 void kill_link(userrec *user,const char* r)
1003 user_hash::iterator iter = clientlist.find(user->nick);
1005 char reason[MAXBUF];
1007 strncpy(reason,r,MAXBUF);
1009 if (strlen(reason)>MAXQUIT)
1011 reason[MAXQUIT-1] = '\0';
1014 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1015 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1016 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1018 if (user->registered == 7) {
1019 FOREACH_MOD OnUserQuit(user,reason);
1020 WriteCommonExcept(user,"QUIT :%s",reason);
1023 user->FlushWriteBuf();
1025 FOREACH_MOD OnUserDisconnect(user);
1029 FOREACH_MOD OnRawSocketClose(user->fd);
1030 SE->DelFd(user->fd);
1031 user->CloseSocket();
1034 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1035 // if they were an oper with +s.
1036 if (user->registered == 7) {
1037 purge_empty_chans(user);
1038 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1040 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1044 if (iter != clientlist.end())
1046 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1048 fd_ref_table[user->fd] = NULL;
1049 clientlist.erase(iter);
1054 void kill_link_silent(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 user->FlushWriteBuf();
1073 if (user->registered == 7) {
1074 FOREACH_MOD OnUserQuit(user,reason);
1075 WriteCommonExcept(user,"QUIT :%s",reason);
1078 FOREACH_MOD OnUserDisconnect(user);
1082 FOREACH_MOD OnRawSocketClose(user->fd);
1083 SE->DelFd(user->fd);
1084 user->CloseSocket();
1087 if (user->registered == 7) {
1088 purge_empty_chans(user);
1091 if (iter != clientlist.end())
1093 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1095 fd_ref_table[user->fd] = NULL;
1096 clientlist.erase(iter);
1102 int main(int argc, char** argv)
1106 log(DEBUG,"*** InspIRCd starting up!");
1107 if (!FileExists(CONFIG_FILE))
1109 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1110 log(DEFAULT,"main: no config");
1111 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1115 for (int i = 1; i < argc; i++)
1117 if (!strcmp(argv[i],"-nofork")) {
1120 if (!strcmp(argv[i],"-wait")) {
1123 if (!strcmp(argv[i],"-nolimit")) {
1129 strlcpy(MyExecutable,argv[0],MAXBUF);
1131 // initialize the lowercase mapping table
1132 for (unsigned int cn = 0; cn < 256; cn++)
1134 // lowercase the uppercase chars
1135 for (unsigned int cn = 65; cn < 91; cn++)
1136 lowermap[cn] = tolower(cn);
1137 // now replace the specific chars for scandanavian comparison
1138 lowermap[(unsigned)'['] = '{';
1139 lowermap[(unsigned)']'] = '}';
1140 lowermap[(unsigned)'\\'] = '|';
1142 if (InspIRCd(argv,argc) == ERROR)
1144 log(DEFAULT,"main: daemon function bailed");
1145 printf("ERROR: could not initialise. Shutting down.\n");
1152 template<typename T> inline string ConvToStr(const T &in)
1155 if (!(tmp << in)) return string();
1159 /* re-allocates a nick in the user_hash after they change nicknames,
1160 * returns a pointer to the new user as it may have moved */
1162 userrec* ReHashNick(char* Old, char* New)
1164 //user_hash::iterator newnick;
1165 user_hash::iterator oldnick = clientlist.find(Old);
1167 log(DEBUG,"ReHashNick: %s %s",Old,New);
1169 if (!strcasecmp(Old,New))
1171 log(DEBUG,"old nick is new nick, skipping");
1172 return oldnick->second;
1175 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1177 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1179 userrec* olduser = oldnick->second;
1180 clientlist[New] = olduser;
1181 clientlist.erase(oldnick);
1183 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1185 return clientlist[New];
1188 /* adds or updates an entry in the whowas list */
1189 void AddWhoWas(userrec* u)
1191 whowas_hash::iterator iter = whowas.find(u->nick);
1192 WhoWasUser *a = new WhoWasUser();
1193 strlcpy(a->nick,u->nick,NICKMAX);
1194 strlcpy(a->ident,u->ident,IDENTMAX);
1195 strlcpy(a->dhost,u->dhost,160);
1196 strlcpy(a->host,u->host,160);
1197 strlcpy(a->fullname,u->fullname,MAXGECOS);
1198 strlcpy(a->server,u->server,256);
1199 a->signon = u->signon;
1201 /* MAX_WHOWAS: max number of /WHOWAS items
1202 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1203 * can be replaced by a newer one
1206 if (iter == whowas.end())
1208 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1210 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1212 // 3600 seconds in an hour ;)
1213 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1215 // delete the old one
1216 if (i->second) delete i->second;
1217 // replace with new one
1219 log(DEBUG,"added WHOWAS entry, purged an old record");
1223 // no space left and user doesnt exist. Don't leave ram in use!
1224 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1229 log(DEBUG,"added fresh WHOWAS entry");
1230 whowas[a->nick] = a;
1235 log(DEBUG,"updated WHOWAS entry");
1236 if (iter->second) delete iter->second;
1242 void* dns_task(void* arg)
1244 userrec* u = (userrec*)arg;
1245 log(DEBUG,"DNS thread for user %s",u->nick);
1250 if (dns1.ReverseLookup(u->ip))
1252 log(DEBUG,"DNS Step 1");
1253 while (!dns1.HasResult())
1257 host = dns1.GetResult();
1260 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1261 if (dns2.ForwardLookup(host))
1263 while (!dns2.HasResult())
1267 ip = dns2.GetResultIP();
1268 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1269 if (ip == std::string(u->ip))
1271 log(DEBUG,"DNS Step 4");
1272 if (host.length() < 160)
1274 log(DEBUG,"DNS Step 5");
1275 strcpy(u->host,host.c_str());
1276 strcpy(u->dhost,host.c_str());
1287 /* add a client connection to the sockets list */
1288 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1292 user_hash::iterator iter;
1294 tempnick = ConvToStr(socket) + "-unknown";
1295 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1297 iter = clientlist.find(tempnick);
1300 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1301 // using one as a registered connection. As theyre per fd, we can also safely assume
1302 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1303 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1304 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1305 // issue in earlier alphas/betas
1306 if (iter != clientlist.end())
1308 userrec* goner = iter->second;
1310 clientlist.erase(iter);
1314 * It is OK to access the value here this way since we know
1315 * it exists, we just created it above.
1317 * At NO other time should you access a value in a map or a
1318 * hash_map this way.
1320 clientlist[tempnick] = new userrec();
1322 NonBlocking(socket);
1323 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1325 clientlist[tempnick]->fd = socket;
1326 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1327 strlcpy(clientlist[tempnick]->host, host,160);
1328 strlcpy(clientlist[tempnick]->dhost, host,160);
1329 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
1330 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1331 clientlist[tempnick]->registered = 0;
1332 clientlist[tempnick]->signon = TIME+dns_timeout;
1333 clientlist[tempnick]->lastping = 1;
1334 clientlist[tempnick]->port = port;
1335 strlcpy(clientlist[tempnick]->ip,ip,16);
1337 // set the registration timeout for this user
1338 unsigned long class_regtimeout = 90;
1339 int class_flood = 0;
1340 long class_threshold = 5;
1341 long class_sqmax = 262144; // 256kb
1342 long class_rqmax = 4096; // 4k
1344 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1346 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1348 class_regtimeout = (unsigned long)i->registration_timeout;
1349 class_flood = i->flood;
1350 clientlist[tempnick]->pingmax = i->pingtime;
1351 class_threshold = i->threshold;
1352 class_sqmax = i->sendqmax;
1353 class_rqmax = i->recvqmax;
1358 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1359 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1360 clientlist[tempnick]->flood = class_flood;
1361 clientlist[tempnick]->threshold = class_threshold;
1362 clientlist[tempnick]->sendqmax = class_sqmax;
1363 clientlist[tempnick]->recvqmax = class_rqmax;
1368 for (int i = 0; i < MAXCHANS; i++)
1369 clientlist[tempnick]->chans.push_back(a);
1371 if (clientlist.size() > SoftLimit)
1373 kill_link(clientlist[tempnick],"No more connections allowed");
1377 if (clientlist.size() >= MAXCLIENTS)
1379 kill_link(clientlist[tempnick],"No more connections allowed");
1383 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1384 // its a pretty big but for the moment valid assumption:
1385 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1386 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1387 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1388 // which for the time being is a physical impossibility (even the largest networks dont have more
1389 // than about 10,000 users on ONE server!)
1390 if ((unsigned)socket > 65534)
1392 kill_link(clientlist[tempnick],"Server is full");
1397 char* e = matches_exception(ip);
1400 char* r = matches_zline(ip);
1403 char reason[MAXBUF];
1404 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1405 kill_link(clientlist[tempnick],reason);
1409 fd_ref_table[socket] = clientlist[tempnick];
1410 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1413 /* shows the message of the day, and any other on-logon stuff */
1414 void FullConnectUser(userrec* user)
1416 stats->statsConnects++;
1417 user->idle_lastmsg = TIME;
1418 log(DEBUG,"ConnectUser: %s",user->nick);
1420 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1422 kill_link(user,"Invalid password");
1427 kill_link(user,"Unauthorised connection");
1431 char match_against[MAXBUF];
1432 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1433 char* e = matches_exception(match_against);
1436 char* r = matches_gline(match_against);
1439 char reason[MAXBUF];
1440 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1441 kill_link_silent(user,reason);
1444 r = matches_kline(user->host);
1447 char reason[MAXBUF];
1448 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1449 kill_link_silent(user,reason);
1455 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1456 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1457 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1458 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1459 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
1460 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1461 std::stringstream v;
1462 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1463 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1464 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1466 std::string data005 = v.str();
1467 FOREACH_MOD On005Numeric(data005);
1468 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1469 // so i'd better split it :)
1470 std::stringstream out(data005);
1471 std::string token = "";
1472 std::string line5 = "";
1473 int token_counter = 0;
1477 line5 = line5 + token + " ";
1479 if ((token_counter >= 13) || (out.eof() == true))
1481 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1488 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1489 // onto the network and produce 'fake direction'
1490 FOREACH_MOD OnUserConnect(user);
1491 FOREACH_MOD OnGlobalConnect(user);
1492 user->registered = 7;
1493 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1497 /* shows the message of the day, and any other on-logon stuff */
1498 void ConnectUser(userrec *user)
1500 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1501 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1503 FullConnectUser(user);
1507 std::string GetVersionString()
1509 char versiondata[MAXBUF];
1511 char dnsengine[] = "multithread";
1513 char dnsengine[] = "singlethread";
1515 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);
1519 void handle_version(char **parameters, int pcnt, userrec *user)
1521 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1525 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1527 for (unsigned int i = 0; i < cmdlist.size(); i++)
1529 if (!strcasecmp(cmdlist[i].command,commandname))
1531 if (cmdlist[i].handler_function)
1533 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1535 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1537 if (cmdlist[i].flags_needed)
1539 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1557 // calls a handler function for a command
1559 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1561 for (unsigned int i = 0; i < cmdlist.size(); i++)
1563 if (!strcasecmp(cmdlist[i].command,commandname))
1565 if (cmdlist[i].handler_function)
1567 if (pcnt>=cmdlist[i].min_params)
1569 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1571 if (cmdlist[i].flags_needed)
1573 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1575 cmdlist[i].handler_function(parameters,pcnt,user);
1580 cmdlist[i].handler_function(parameters,pcnt,user);
1590 void force_nickchange(userrec* user,const char* newnick)
1597 FOREACH_RESULT(OnUserPreNick(user,newnick));
1599 stats->statsCollisions++;
1600 kill_link(user,"Nickname collision");
1603 if (matches_qline(newnick))
1605 stats->statsCollisions++;
1606 kill_link(user,"Nickname collision");
1614 strncpy(nick,newnick,MAXBUF);
1616 if (user->registered == 7)
1620 handle_nick(pars,1,user);
1626 int process_parameters(char **command_p,char *parameters)
1629 int q = strlen(parameters);
1632 /* no parameters, command_p invalid! */
1635 if (parameters[0] == ':')
1637 command_p[0] = parameters+1;
1642 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1644 /* only one parameter */
1645 command_p[0] = parameters;
1646 if (parameters[0] == ':')
1648 if (strchr(parameters,' ') != NULL)
1656 command_p[j++] = parameters;
1657 for (int i = 0; i <= q; i++)
1659 if (parameters[i] == ' ')
1661 command_p[j++] = parameters+i+1;
1662 parameters[i] = '\0';
1663 if (command_p[j-1][0] == ':')
1665 *command_p[j-1]++; /* remove dodgy ":" */
1667 /* parameter like this marks end of the sequence */
1671 return j; /* returns total number of items in the list */
1674 void process_command(userrec *user, char* cmd)
1678 char *command_p[127];
1679 char p[MAXBUF], temp[MAXBUF];
1680 int j, items, cmd_found;
1682 for (int i = 0; i < 127; i++)
1683 command_p[i] = NULL;
1698 int total_params = 0;
1701 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1703 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1706 // found a 'trailing', we dont count them after this.
1714 // another phidjit bug...
1715 if (total_params > 126)
1717 *(strchr(cmd,' ')) = '\0';
1718 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1722 strlcpy(temp,cmd,MAXBUF);
1724 std::string tmp = cmd;
1725 for (int i = 0; i <= MODCOUNT; i++)
1727 std::string oldtmp = tmp;
1728 modules[i]->OnServerRaw(tmp,true,user);
1731 log(DEBUG,"A Module changed the input string!");
1732 log(DEBUG,"New string: %s",tmp.c_str());
1733 log(DEBUG,"Old string: %s",oldtmp.c_str());
1737 strlcpy(cmd,tmp.c_str(),MAXBUF);
1738 strlcpy(temp,cmd,MAXBUF);
1740 if (!strchr(cmd,' '))
1742 /* no parameters, lets skip the formalities and not chop up
1744 log(DEBUG,"About to preprocess command with no params");
1746 command_p[0] = NULL;
1748 for (unsigned int i = 0; i <= strlen(cmd); i++)
1750 cmd[i] = toupper(cmd[i]);
1758 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1759 for (unsigned int i = 0; i < strlen(temp); i++)
1761 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1767 /* split the full string into a command plus parameters */
1771 if (strchr(cmd,' '))
1773 for (unsigned int i = 0; i <= strlen(cmd); i++)
1775 /* capitalise the command ONLY, leave params intact */
1776 cmd[i] = toupper(cmd[i]);
1777 /* are we nearly there yet?! :P */
1781 parameters = cmd+i+1;
1789 for (unsigned int i = 0; i <= strlen(cmd); i++)
1791 cmd[i] = toupper(cmd[i]);
1798 if (strlen(command)>MAXCOMMAND)
1800 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1804 for (unsigned int x = 0; x < strlen(command); x++)
1806 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1808 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1810 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1812 stats->statsUnknown++;
1813 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1820 for (unsigned int i = 0; i != cmdlist.size(); i++)
1822 if (cmdlist[i].command[0])
1824 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1830 items = process_parameters(command_p,parameters);
1835 command_p[0] = NULL;
1841 command_p[0] = NULL;
1846 /* activity resets the ping pending timer */
1847 user->nping = TIME + user->pingmax;
1848 if ((items) < cmdlist[i].min_params)
1850 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1851 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1854 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1856 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1857 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1861 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1863 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1864 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1868 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1870 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1872 if ((!isnick(user->nick)) || (user->registered != 7))
1874 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1875 WriteServ(user->fd,"451 %s :You have not registered",command);
1879 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1881 std::stringstream dcmds(DisabledCommands);
1882 while (!dcmds.eof())
1884 std::string thiscmd;
1886 if (!strcasecmp(thiscmd.c_str(),command))
1888 // command is disabled!
1889 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1894 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1896 if (cmdlist[i].handler_function)
1899 /* ikky /stats counters */
1902 cmdlist[i].use_count++;
1903 cmdlist[i].total_bytes+=strlen(temp);
1907 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1908 if (MOD_RESULT == 1) {
1912 /* WARNING: nothing may come after the
1913 * command handler call, as the handler
1914 * may free the user structure! */
1916 cmdlist[i].handler_function(command_p,items,user);
1922 WriteServ(user->fd,"451 %s :You have not registered",command);
1930 if ((!cmd_found) && (user))
1932 stats->statsUnknown++;
1933 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1937 bool removecommands(const char* source)
1939 bool go_again = true;
1943 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1945 if (!strcmp(i->source,source))
1947 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1958 void process_buffer(const char* cmdbuf,userrec *user)
1962 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1968 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1975 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1977 strlcpy(cmd,cmdbuf,MAXBUF);
1982 int sl = strlen(cmd)-1;
1983 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1988 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1993 while (cmd[sl] == ' ') // strip trailing spaces
2003 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2005 if ((user) && (cmd))
2007 process_command(user,cmd);
2011 char MODERR[MAXBUF];
2018 void erase_factory(int j)
2021 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2026 factory.push_back(NULL);
2033 void erase_module(int j)
2036 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2042 modules.push_back(NULL);
2048 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2052 module_names.erase(v);
2060 bool UnloadModule(const char* filename)
2062 std::string filename_str = filename;
2063 for (unsigned int j = 0; j != module_names.size(); j++)
2065 if (module_names[j] == filename_str)
2067 if (modules[j]->GetVersion().Flags & VF_STATIC)
2069 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2070 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2073 /* Give the module a chance to tidy out all its metadata */
2074 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2076 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2078 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2080 modules[j]->OnCleanup(TYPE_USER,u->second);
2082 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2084 log(DEBUG,"Deleting module...");
2086 log(DEBUG,"Erasing module entry...");
2088 log(DEBUG,"Removing dependent commands...");
2089 removecommands(filename);
2090 log(DEFAULT,"Module %s unloaded",filename);
2095 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2096 snprintf(MODERR,MAXBUF,"Module not loaded");
2100 bool LoadModule(const char* filename)
2102 char modfile[MAXBUF];
2104 snprintf(modfile,MAXBUF,"%s",filename);
2106 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2108 std::string filename_str = filename;
2110 if (!DirValid(modfile))
2112 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2113 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2117 log(DEBUG,"Loading module: %s",modfile);
2119 if (FileExists(modfile))
2122 for (unsigned int j = 0; j < module_names.size(); j++)
2124 if (module_names[j] == filename_str)
2126 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2127 snprintf(MODERR,MAXBUF,"Module already loaded");
2131 ircd_module* a = new ircd_module(modfile);
2132 factory[MODCOUNT+1] = a;
2133 if (factory[MODCOUNT+1]->LastError())
2135 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2136 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2140 if (factory[MODCOUNT+1]->factory)
2142 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2143 modules[MODCOUNT+1] = m;
2144 /* save the module and the module's classfactory, if
2145 * this isnt done, random crashes can occur :/ */
2146 module_names.push_back(filename);
2150 log(DEFAULT,"Unable to load %s",modfile);
2151 snprintf(MODERR,MAXBUF,"Factory function failed!");
2158 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2159 snprintf(MODERR,MAXBUF,"Module file could not be found");
2164 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2170 char configToken[MAXBUF];
2171 int clientportcount = 0;
2172 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2174 ConfValue("bind","port",count,configToken,&config_f);
2175 ConfValue("bind","address",count,Addr,&config_f);
2176 ConfValue("bind","type",count,Type,&config_f);
2177 if (strcmp(Type,"servers"))
2179 // modules handle server bind types now,
2180 // its not a typo in the strcmp.
2181 ports[clientportcount] = atoi(configToken);
2182 strlcpy(addrs[clientportcount],Addr,256);
2184 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2187 portCount = clientportcount;
2189 for (int count = 0; count < portCount; count++)
2191 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2193 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2196 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2198 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2200 else /* well we at least bound to one socket so we'll continue */
2206 /* if we didn't bind to anything then abort */
2207 if (!boundPortCount)
2209 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2210 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2214 return boundPortCount;
2217 int InspIRCd(char** argv, int argc)
2219 bool expire_run = false;
2220 std::vector<int> activefds;
2224 InspSocket* s = NULL;
2225 InspSocket* s_del = NULL;
2227 unsigned int numberactive;
2228 sockaddr_in sock_us; // our port number
2229 socklen_t uslen; // length of our port number
2231 /* Beta 7 moved all this stuff out of the main function
2232 * into smaller sub-functions, much tidier -- Brain
2234 OpenLog(argv, argc);
2236 SetupCommandTable();
2237 ReadConfig(true,NULL);
2238 AddServerName(Config->ServerName);
2240 boundPortCount = BindPorts();
2243 startup_time = time(NULL);
2246 ConfValue("pid","file",0,PID,&config_f);
2247 // write once here, to try it out and make sure its ok
2252 if (DaemonSeed() == ERROR)
2254 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2259 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2260 * initialize the socket engine.
2262 SE = new SocketEngine();
2264 /* We must load the modules AFTER initializing the socket engine, now */
2267 printf("\nInspIRCd is now running!\n");
2270 freopen("/dev/null","w",stdout);
2271 freopen("/dev/null","w",stderr);
2274 /* Add the listening sockets used for client inbound connections
2275 * to the socket engine
2277 for (int count = 0; count < portCount; count++)
2278 SE->AddFd(openSockfd[count],true,X_LISTEN);
2282 /* main loop, this never returns */
2285 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2286 * Once per loop iteration is pleanty.
2291 /* Run background module timers every few seconds
2292 * (the docs say modules shouldnt rely on accurate
2293 * timing using this event, so we dont have to
2294 * time this exactly).
2296 if (((TIME % 8) == 0) && (!expire_run))
2299 FOREACH_MOD OnBackgroundTimer(TIME);
2303 if ((TIME % 8) == 1)
2306 /* Once a second, do the background processing */
2307 if (TIME != OLDTIME)
2308 while (DoBackgroundUserStuff(TIME));
2310 /* Call the socket engine to wait on the active
2311 * file descriptors. The socket engine has everything's
2312 * descriptors in its list... dns, modules, users,
2313 * servers... so its nice and easy, just one call.
2315 SE->Wait(activefds);
2318 * Now process each of the fd's. For users, we have a fast
2319 * lookup table which can find a user by file descriptor, so
2320 * processing them by fd isnt expensive. If we have a lot of
2321 * listening ports or module sockets though, things could get
2324 numberactive = activefds.size();
2325 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2327 int socket_type = SE->GetType(activefds[activefd]);
2328 switch (socket_type)
2330 case X_ESTAB_CLIENT:
2332 cu = fd_ref_table[activefds[activefd]];
2338 case X_ESTAB_MODULE:
2340 /* Process module-owned sockets.
2341 * Modules are encouraged to inherit their sockets from
2342 * InspSocket so we can process them neatly like this.
2344 s = socket_ref[activefds[activefd]];
2346 if ((s) && (!s->Poll()))
2348 log(DEBUG,"Socket poll returned false, close and bail");
2349 SE->DelFd(s->GetFd());
2350 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2352 s_del = (InspSocket*)*a;
2353 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2355 module_sockets.erase(a);
2367 /* When we are using single-threaded dns,
2368 * the sockets for dns end up in our mainloop.
2369 * When we are using multi-threaded dns,
2370 * each thread has its own basic poll() loop
2371 * within it, making them 'fire and forget'
2372 * and independent of the mainloop.
2374 #ifndef THREADED_DNS
2375 dns_poll(activefds[activefd]);
2381 /* It's a listener */
2382 uslen = sizeof(sock_us);
2383 length = sizeof(client);
2384 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2385 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2387 in_port = ntohs(sock_us.sin_port);
2388 log(DEBUG,"Accepted socket %d",incomingSockfd);
2389 target = (char*)inet_ntoa(client.sin_addr);
2390 /* Years and years ago, we used to resolve here
2391 * using gethostbyaddr(). That is sucky and we
2392 * don't do that any more...
2394 if (incomingSockfd >= 0)
2396 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2397 stats->statsAccept++;
2398 AddClient(incomingSockfd, target, in_port, false, target);
2399 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2403 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2404 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2405 stats->statsRefused++;
2410 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2411 shutdown(incomingSockfd,2);
2412 close(incomingSockfd);
2417 /* Something went wrong if we're in here.
2418 * In fact, so wrong, im not quite sure
2419 * what we would do, so for now, its going
2420 * to safely do bugger all.
2427 /* This is never reached -- we hope! */