1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
21 #include "inspircd_config.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
33 #include <ext/hash_map>
55 #include "inspstring.h"
57 #include "helperfuncs.h"
59 #include "socketengine.h"
60 #include "userprocess.h"
64 int LogLevel = DEFAULT;
65 char ServerName[MAXBUF];
67 char ServerDesc[MAXBUF];
68 char AdminName[MAXBUF];
69 char AdminEmail[MAXBUF];
70 char AdminNick[MAXBUF];
72 char restartpass[MAXBUF];
76 char PrefixQuit[MAXBUF];
77 char DieValue[MAXBUF];
78 char DNSServer[MAXBUF];
81 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
82 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
84 time_t startup_time = time(NULL);
85 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
86 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
87 unsigned int SoftLimit = MAXCLIENTS;
88 extern int MaxWhoResults;
92 char DisabledCommands[MAXBUF];
94 bool AllowHalfop = true;
95 bool AllowProtect = true;
96 bool AllowFounder = true;
98 extern std::vector<Module*> modules;
99 std::vector<std::string> module_names;
100 extern std::vector<ircd_module*> factory;
102 std::vector<InspSocket*> module_sockets;
105 int openSockfd[MAXSOCKS];
107 bool unlimitcore = false;
108 struct sockaddr_in client,server;
109 char addrs[MAXBUF][255];
111 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
113 extern InspSocket* socket_ref[65535];
115 time_t TIME = time(NULL), OLDTIME = time(NULL);
117 SocketEngine* SE = NULL;
119 bool has_been_netsplit = false;
120 extern std::vector<std::string> include_stack;
122 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
123 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
124 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
125 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
126 typedef std::deque<command_t> command_table;
127 typedef std::map<std::string,time_t> autoconnects;
128 typedef std::vector<std::string> servernamelist;
130 // This table references users by file descriptor.
131 // its an array to make it VERY fast, as all lookups are referenced
132 // by an integer, meaning there is no need for a scan/search operation.
133 userrec* fd_ref_table[65536];
135 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
137 Server* MyServer = new Server;
141 user_hash clientlist;
144 command_table cmdlist;
145 autoconnects autoconns;
151 servernamelist servernames;
153 struct linger linger = { 0 };
154 char MyExecutable[1024];
155 int boundPortCount = 0;
156 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
158 char ModPath[MAXBUF];
162 int has_channel(userrec *u, chanrec *c);
163 int usercount(chanrec *c);
164 int usercount_i(chanrec *c);
165 char* Passwd(userrec *user);
166 bool IsDenied(userrec *user);
167 void AddWhoWas(userrec* u);
169 std::stringstream config_f(stringstream::in | stringstream::out);
171 std::vector<userrec*> all_opers;
175 void AddOper(userrec* user)
177 log(DEBUG,"Oper added to optimization list");
178 all_opers.push_back(user);
181 void AddServerName(std::string servername)
183 log(DEBUG,"Adding server name: %s",servername.c_str());
184 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
186 if (*a == servername)
189 servernames.push_back(servername);
192 const char* FindServerNamePtr(std::string servername)
194 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
196 if (*a == servername)
199 AddServerName(servername);
200 return FindServerNamePtr(servername);
203 void DeleteOper(userrec* user)
205 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
209 log(DEBUG,"Oper removed from optimization list");
216 std::string GetRevision()
218 char Revision[] = "$Revision$";
221 char *v2 = strtok_r(s1," ",&savept);
223 v2 = strtok_r(s1," ",&savept);
225 return std::string(v2);
229 std::string getservername()
234 std::string getserverdesc()
239 std::string getnetworkname()
244 std::string getadminname()
249 std::string getadminemail()
254 std::string getadminnick()
259 void ReadConfig(bool bail, userrec* user)
261 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
262 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
264 std::stringstream errstr;
265 include_stack.clear();
267 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
270 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
273 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
281 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
282 while (!errstr.eof())
284 errstr.getline(dataline,1024);
285 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
290 WriteOpers("There were errors in the configuration file:");
291 while (!errstr.eof())
293 errstr.getline(dataline,1024);
294 WriteOpers(dataline);
301 ConfValue("server","name",0,ServerName,&config_f);
302 ConfValue("server","description",0,ServerDesc,&config_f);
303 ConfValue("server","network",0,Network,&config_f);
304 ConfValue("admin","name",0,AdminName,&config_f);
305 ConfValue("admin","email",0,AdminEmail,&config_f);
306 ConfValue("admin","nick",0,AdminNick,&config_f);
307 ConfValue("files","motd",0,motd,&config_f);
308 ConfValue("files","rules",0,rules,&config_f);
309 ConfValue("power","diepass",0,diepass,&config_f);
310 ConfValue("power","pause",0,pauseval,&config_f);
311 ConfValue("power","restartpass",0,restartpass,&config_f);
312 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
313 ConfValue("die","value",0,DieValue,&config_f);
314 ConfValue("options","loglevel",0,dbg,&config_f);
315 ConfValue("options","netbuffersize",0,NB,&config_f);
316 ConfValue("options","maxwho",0,MW,&config_f);
317 ConfValue("options","allowhalfop",0,AH,&config_f);
318 ConfValue("options","allowprotect",0,AP,&config_f);
319 ConfValue("options","allowfounder",0,AF,&config_f);
320 ConfValue("dns","server",0,DNSServer,&config_f);
321 ConfValue("dns","timeout",0,DNT,&config_f);
322 ConfValue("options","moduledir",0,ModPath,&config_f);
323 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
324 ConfValue("options","somaxconn",0,MCON,&config_f);
325 ConfValue("options","softlimit",0,SLIMT,&config_f);
327 SoftLimit = atoi(SLIMT);
328 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
330 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
331 SoftLimit = MAXCLIENTS;
333 MaxConn = atoi(MCON);
334 if (MaxConn > SOMAXCONN)
335 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
336 NetBufferSize = atoi(NB);
337 MaxWhoResults = atoi(MW);
338 dns_timeout = atoi(DNT);
344 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
346 strlcpy(ModPath,MOD_PATH,MAXBUF);
347 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
348 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
349 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
350 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
352 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
353 NetBufferSize = 10240;
355 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
357 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
360 if (!strcmp(dbg,"debug"))
362 if (!strcmp(dbg,"verbose"))
364 if (!strcmp(dbg,"default"))
366 if (!strcmp(dbg,"sparse"))
368 if (!strcmp(dbg,"none"))
371 log(DEFAULT,"Reading message of the day...");
372 readfile(RULES,rules);
373 log(DEFAULT,"Reading connect classes...");
375 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
378 ConfValue("connect","allow",i,Value,&config_f);
379 ConfValue("connect","timeout",i,timeout,&config_f);
380 ConfValue("connect","flood",i,flood,&config_f);
381 ConfValue("connect","pingfreq",i,pfreq,&config_f);
382 ConfValue("connect","threshold",i,thold,&config_f);
383 ConfValue("connect","sendq",i,sqmax,&config_f);
384 ConfValue("connect","recvq",i,rqmax,&config_f);
387 strlcpy(c.host,Value,MAXBUF);
389 strlcpy(Value,"",MAXBUF);
390 ConfValue("connect","password",i,Value,&config_f);
391 strlcpy(c.pass,Value,MAXBUF);
392 c.registration_timeout = 90; // default is 2 minutes
394 c.flood = atoi(flood);
396 c.sendqmax = 262144; // 256k
397 c.recvqmax = 4096; // 4k
400 c.threshold = atoi(thold);
404 c.sendqmax = atoi(sqmax);
408 c.recvqmax = atoi(rqmax);
412 c.registration_timeout = atoi(timeout);
416 c.pingtime = atoi(pfreq);
418 Classes.push_back(c);
419 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);
423 ConfValue("connect","deny",i,Value,&config_f);
424 strlcpy(c.host,Value,MAXBUF);
426 Classes.push_back(c);
427 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
431 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
432 read_xline_defaults();
433 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
437 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
439 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
440 ConfValue("link","name",i,Link_ServerName,&config_f);
441 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
442 if (strcmp(Link_AConn,""))
444 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
449 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
452 log(DEFAULT,"Adding and removing modules due to rehash...");
454 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
456 // store the old module names
457 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
459 old_module_names.push_back(*t);
462 // get the new module names
463 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
465 ConfValue("module","name",count2,Value,&config_f);
466 new_module_names.push_back(Value);
469 // now create a list of new modules that are due to be loaded
470 // and a seperate list of modules which are due to be unloaded
471 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
474 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
480 added_modules.push_back(*_new);
482 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
485 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
491 removed_modules.push_back(*oldm);
493 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
495 int rem = 0, add = 0;
496 if (!removed_modules.empty())
497 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
499 if (UnloadModule(removing->c_str()))
501 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
502 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
507 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
510 if (!added_modules.empty())
511 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
513 if (LoadModule(adding->c_str()))
515 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
516 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
521 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
524 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());
529 /* add a channel to a user, creating the record for it if needed and linking
530 * it to the user record */
532 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
534 if ((!user) || (!cn))
536 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
544 strncpy(cname,cn,MAXBUF);
546 // we MUST declare this wherever we use FOREACH_RESULT
549 if (strlen(cname) > CHANMAX)
551 cname[CHANMAX] = '\0';
554 log(DEBUG,"add_channel: %s %s",user->nick,cname);
556 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
558 return NULL; // already on the channel!
562 if (!FindChan(cname))
564 if (!strcasecmp(ServerName,user->server))
567 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
568 if (MOD_RESULT == 1) {
573 /* create a new one */
574 log(DEBUG,"add_channel: creating: %s",cname);
576 chanlist[cname] = new chanrec();
578 strlcpy(chanlist[cname]->name, cname,CHANMAX);
579 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
580 chanlist[cname]->created = TIME;
581 strcpy(chanlist[cname]->topic, "");
582 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
583 chanlist[cname]->topicset = 0;
584 Ptr = chanlist[cname];
585 log(DEBUG,"add_channel: created: %s",cname);
586 /* set created to 2 to indicate user
587 * is the first in the channel
588 * and should be given ops */
594 /* channel exists, just fish out a pointer to its struct */
595 Ptr = FindChan(cname);
598 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
600 // remote users are allowed us to bypass channel modes
601 // and bans (used by servers)
602 if (!strcasecmp(ServerName,user->server))
604 log(DEBUG,"Not overriding...");
606 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
607 if (MOD_RESULT == 1) {
610 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
614 log(DEBUG,"add_channel: checking key, invite, etc");
616 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
621 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
624 log(DEBUG,"add_channel: no key given in JOIN");
625 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
630 if (strcasecmp(key,Ptr->key))
632 log(DEBUG,"add_channel: bad key given in JOIN");
633 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
638 log(DEBUG,"add_channel: no key");
641 FOREACH_RESULT(OnCheckInvite(user, Ptr));
644 if (Ptr->binarymodes & CM_INVITEONLY)
646 log(DEBUG,"add_channel: channel is +i");
647 if (user->IsInvited(Ptr->name))
649 /* user was invited to channel */
650 /* there may be an optional channel NOTICE here */
654 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
658 log(DEBUG,"add_channel: channel is not +i");
661 FOREACH_RESULT(OnCheckLimit(user, Ptr));
666 if (usercount(Ptr) >= Ptr->limit)
668 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
673 log(DEBUG,"add_channel: about to walk banlist");
675 FOREACH_RESULT(OnCheckBan(user, Ptr));
678 /* check user against the channel banlist */
681 if (Ptr->bans.size())
683 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
685 if (match(user->GetFullHost(),i->data))
687 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
693 log(DEBUG,"add_channel: bans checked");
701 user->RemoveInvite(Ptr->name);
704 log(DEBUG,"add_channel: invites removed");
709 log(DEBUG,"Overridden checks");
717 log(DEBUG,"Passed channel checks");
719 for (unsigned int index =0; index < user->chans.size(); index++)
721 if (user->chans[index].channel == NULL)
723 return ForceChan(Ptr,user->chans[index],user,created);
726 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
727 * and put the channel in here. Same for remote users which are not bound by
728 * the channel limits. Otherwise, nope, youre boned.
730 if (strcasecmp(user->server,ServerName))
733 chanrec* c = ForceChan(Ptr,a,user,created);
734 user->chans.push_back(a);
737 else if (strchr(user->modes,'o'))
739 /* Oper allows extension up to the OPERMAXCHANS value */
740 if (user->chans.size() < OPERMAXCHANS)
743 chanrec* c = ForceChan(Ptr,a,user,created);
744 user->chans.push_back(a);
748 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
749 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
753 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
757 /* first user in is given ops */
758 a.uc_modes = UCMODE_OP;
765 Ptr->AddUser((char*)user);
766 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
767 log(DEBUG,"Sent JOIN to client");
770 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
771 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
774 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
775 FOREACH_MOD OnUserJoin(user,Ptr);
779 /* remove a channel from a users record, and remove the record from memory
780 * if the channel has become empty */
782 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
784 if ((!user) || (!cname))
786 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
792 if ((!cname) || (!user))
797 Ptr = FindChan(cname);
804 FOREACH_MOD OnUserPart(user,Ptr);
805 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
807 for (unsigned int i =0; i < user->chans.size(); i++)
809 /* zap it from the channel list of the user */
810 if (user->chans[i].channel == Ptr)
814 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
818 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
820 user->chans[i].uc_modes = 0;
821 user->chans[i].channel = NULL;
822 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
827 Ptr->DelUser((char*)user);
829 /* if there are no users left on the channel */
832 chan_hash::iterator iter = chanlist.find(Ptr->name);
834 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
836 /* kill the record */
837 if (iter != chanlist.end())
839 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
841 chanlist.erase(iter);
849 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
851 if ((!src) || (!user) || (!Ptr) || (!reason))
853 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
857 if ((!Ptr) || (!user) || (!src))
862 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
864 if (!has_channel(user,Ptr))
866 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
871 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
872 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
875 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
877 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
879 if (cstatus(src,Ptr) == STATUS_HOP)
881 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
885 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
892 if (!is_uline(src->server))
895 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
900 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
902 for (unsigned int i =0; i < user->chans.size(); i++)
904 /* zap it from the channel list of the user */
905 if (user->chans[i].channel)
906 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
908 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
909 user->chans[i].uc_modes = 0;
910 user->chans[i].channel = NULL;
911 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
916 Ptr->DelUser((char*)user);
918 /* if there are no users left on the channel */
921 chan_hash::iterator iter = chanlist.find(Ptr->name);
923 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
925 /* kill the record */
926 if (iter != chanlist.end())
928 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
930 chanlist.erase(iter);
938 /* This function pokes and hacks at a parameter list like the following:
940 * PART #winbot,#darkgalaxy :m00!
942 * to turn it into a series of individual calls like this:
945 * PART #darkgalaxy :m00!
947 * The seperate calls are sent to a callback function provided by the caller
948 * (the caller will usually call itself recursively). The callback function
949 * must be a command handler. Calling this function on a line with no list causes
950 * no action to be taken. You must provide a starting and ending parameter number
951 * where the range of the list can be found, useful if you have a terminating
952 * parameter as above which is actually not part of the list, or parameters
953 * before the actual list as well. This code is used by many functions which
954 * can function as "one to list" (see the RFC) */
956 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
961 char blog[32][MAXBUF];
962 char blog2[32][MAXBUF];
963 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
967 for (int i = 0; i <32; i++)
970 for (int i = 0; i <32; i++)
974 for (int i = 0; i <10; i++)
983 if (pcnt > 1) /* we have a key to copy */
985 strlcpy(keystr,parameters[1],MAXBUF);
989 if (!parameters[start])
993 if (!strchr(parameters[start],','))
998 for (int i = start; i <= end; i++)
1002 strlcat(plist,parameters[i],MAXBUF);
1010 for (int i = 0; i < t; i++)
1012 if (plist[i] == ',')
1015 strlcpy(blog[j++],param,MAXBUF);
1019 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1024 strlcpy(blog[j++],param,MAXBUF);
1027 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1032 if ((joins) && (keystr))
1034 if (strchr(keystr,','))
1038 t2 = strlen(keystr);
1039 for (int i = 0; i < t2; i++)
1041 if (keystr[i] == ',')
1044 strlcpy(blog2[j++],param,MAXBUF);
1048 strlcpy(blog2[j++],param,MAXBUF);
1053 for (j = 0; j < total; j++)
1059 for (q = end; q < pcnt-1; q++)
1061 if (parameters[q+1])
1063 pars[q-end+1] = parameters[q+1];
1066 if ((joins) && (parameters[1]))
1077 /* repeatedly call the function with the hacked parameter list */
1078 if ((joins) && (pcnt > 1))
1082 // pars[1] already set up and containing key from blog2[j]
1087 pars[1] = parameters[1];
1093 fn(pars,pcnt-(end-start),u);
1102 void kill_link(userrec *user,const char* r)
1104 user_hash::iterator iter = clientlist.find(user->nick);
1106 char reason[MAXBUF];
1108 strncpy(reason,r,MAXBUF);
1110 if (strlen(reason)>MAXQUIT)
1112 reason[MAXQUIT-1] = '\0';
1115 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1116 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1117 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1119 if (user->registered == 7) {
1120 FOREACH_MOD OnUserQuit(user,reason);
1121 WriteCommonExcept(user,"QUIT :%s",reason);
1124 user->FlushWriteBuf();
1126 FOREACH_MOD OnUserDisconnect(user);
1130 FOREACH_MOD OnRawSocketClose(user->fd);
1131 SE->DelFd(user->fd);
1132 user->CloseSocket();
1135 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1136 // if they were an oper with +s.
1137 if (user->registered == 7) {
1138 purge_empty_chans(user);
1139 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1140 if (!strcmp(user->server,ServerName))
1141 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1145 if (iter != clientlist.end())
1147 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1149 fd_ref_table[user->fd] = NULL;
1150 clientlist.erase(iter);
1155 void kill_link_silent(userrec *user,const char* r)
1157 user_hash::iterator iter = clientlist.find(user->nick);
1159 char reason[MAXBUF];
1161 strncpy(reason,r,MAXBUF);
1163 if (strlen(reason)>MAXQUIT)
1165 reason[MAXQUIT-1] = '\0';
1168 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1169 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1170 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1172 user->FlushWriteBuf();
1174 if (user->registered == 7) {
1175 FOREACH_MOD OnUserQuit(user,reason);
1176 WriteCommonExcept(user,"QUIT :%s",reason);
1179 FOREACH_MOD OnUserDisconnect(user);
1183 FOREACH_MOD OnRawSocketClose(user->fd);
1184 SE->DelFd(user->fd);
1185 user->CloseSocket();
1188 if (user->registered == 7) {
1189 purge_empty_chans(user);
1192 if (iter != clientlist.end())
1194 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1196 fd_ref_table[user->fd] = NULL;
1197 clientlist.erase(iter);
1203 int main(int argc, char** argv)
1207 log(DEBUG,"*** InspIRCd starting up!");
1208 if (!FileExists(CONFIG_FILE))
1210 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1211 log(DEFAULT,"main: no config");
1212 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1216 for (int i = 1; i < argc; i++)
1218 if (!strcmp(argv[i],"-nofork")) {
1221 if (!strcmp(argv[i],"-wait")) {
1224 if (!strcmp(argv[i],"-nolimit")) {
1230 strlcpy(MyExecutable,argv[0],MAXBUF);
1232 // initialize the lowercase mapping table
1233 for (unsigned int cn = 0; cn < 256; cn++)
1235 // lowercase the uppercase chars
1236 for (unsigned int cn = 65; cn < 91; cn++)
1237 lowermap[cn] = tolower(cn);
1238 // now replace the specific chars for scandanavian comparison
1239 lowermap[(unsigned)'['] = '{';
1240 lowermap[(unsigned)']'] = '}';
1241 lowermap[(unsigned)'\\'] = '|';
1243 if (InspIRCd(argv,argc) == ERROR)
1245 log(DEFAULT,"main: daemon function bailed");
1246 printf("ERROR: could not initialise. Shutting down.\n");
1253 template<typename T> inline string ConvToStr(const T &in)
1256 if (!(tmp << in)) return string();
1260 /* re-allocates a nick in the user_hash after they change nicknames,
1261 * returns a pointer to the new user as it may have moved */
1263 userrec* ReHashNick(char* Old, char* New)
1265 //user_hash::iterator newnick;
1266 user_hash::iterator oldnick = clientlist.find(Old);
1268 log(DEBUG,"ReHashNick: %s %s",Old,New);
1270 if (!strcasecmp(Old,New))
1272 log(DEBUG,"old nick is new nick, skipping");
1273 return oldnick->second;
1276 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1278 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1280 userrec* olduser = oldnick->second;
1281 clientlist[New] = olduser;
1282 clientlist.erase(oldnick);
1284 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1286 return clientlist[New];
1289 /* adds or updates an entry in the whowas list */
1290 void AddWhoWas(userrec* u)
1292 whowas_hash::iterator iter = whowas.find(u->nick);
1293 WhoWasUser *a = new WhoWasUser();
1294 strlcpy(a->nick,u->nick,NICKMAX);
1295 strlcpy(a->ident,u->ident,IDENTMAX);
1296 strlcpy(a->dhost,u->dhost,160);
1297 strlcpy(a->host,u->host,160);
1298 strlcpy(a->fullname,u->fullname,MAXGECOS);
1299 strlcpy(a->server,u->server,256);
1300 a->signon = u->signon;
1302 /* MAX_WHOWAS: max number of /WHOWAS items
1303 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1304 * can be replaced by a newer one
1307 if (iter == whowas.end())
1309 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1311 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1313 // 3600 seconds in an hour ;)
1314 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1316 // delete the old one
1317 if (i->second) delete i->second;
1318 // replace with new one
1320 log(DEBUG,"added WHOWAS entry, purged an old record");
1324 // no space left and user doesnt exist. Don't leave ram in use!
1325 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1330 log(DEBUG,"added fresh WHOWAS entry");
1331 whowas[a->nick] = a;
1336 log(DEBUG,"updated WHOWAS entry");
1337 if (iter->second) delete iter->second;
1343 void* dns_task(void* arg)
1345 userrec* u = (userrec*)arg;
1346 log(DEBUG,"DNS thread for user %s",u->nick);
1351 if (dns1.ReverseLookup(u->ip))
1353 log(DEBUG,"DNS Step 1");
1354 while (!dns1.HasResult())
1358 host = dns1.GetResult();
1361 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1362 if (dns2.ForwardLookup(host))
1364 while (!dns2.HasResult())
1368 ip = dns2.GetResultIP();
1369 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1370 if (ip == std::string(u->ip))
1372 log(DEBUG,"DNS Step 4");
1373 if (host.length() < 160)
1375 log(DEBUG,"DNS Step 5");
1376 strcpy(u->host,host.c_str());
1377 strcpy(u->dhost,host.c_str());
1388 /* add a client connection to the sockets list */
1389 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1393 user_hash::iterator iter;
1395 tempnick = ConvToStr(socket) + "-unknown";
1396 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1398 iter = clientlist.find(tempnick);
1401 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1402 // using one as a registered connection. As theyre per fd, we can also safely assume
1403 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1404 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1405 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1406 // issue in earlier alphas/betas
1407 if (iter != clientlist.end())
1409 userrec* goner = iter->second;
1411 clientlist.erase(iter);
1415 * It is OK to access the value here this way since we know
1416 * it exists, we just created it above.
1418 * At NO other time should you access a value in a map or a
1419 * hash_map this way.
1421 clientlist[tempnick] = new userrec();
1423 NonBlocking(socket);
1424 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1426 clientlist[tempnick]->fd = socket;
1427 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1428 strlcpy(clientlist[tempnick]->host, host,160);
1429 strlcpy(clientlist[tempnick]->dhost, host,160);
1430 clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1431 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1432 clientlist[tempnick]->registered = 0;
1433 clientlist[tempnick]->signon = TIME+dns_timeout;
1434 clientlist[tempnick]->lastping = 1;
1435 clientlist[tempnick]->port = port;
1436 strlcpy(clientlist[tempnick]->ip,ip,16);
1438 // set the registration timeout for this user
1439 unsigned long class_regtimeout = 90;
1440 int class_flood = 0;
1441 long class_threshold = 5;
1442 long class_sqmax = 262144; // 256kb
1443 long class_rqmax = 4096; // 4k
1445 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1447 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1449 class_regtimeout = (unsigned long)i->registration_timeout;
1450 class_flood = i->flood;
1451 clientlist[tempnick]->pingmax = i->pingtime;
1452 class_threshold = i->threshold;
1453 class_sqmax = i->sendqmax;
1454 class_rqmax = i->recvqmax;
1459 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1460 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1461 clientlist[tempnick]->flood = class_flood;
1462 clientlist[tempnick]->threshold = class_threshold;
1463 clientlist[tempnick]->sendqmax = class_sqmax;
1464 clientlist[tempnick]->recvqmax = class_rqmax;
1469 for (int i = 0; i < MAXCHANS; i++)
1470 clientlist[tempnick]->chans.push_back(a);
1472 if (clientlist.size() > SoftLimit)
1474 kill_link(clientlist[tempnick],"No more connections allowed");
1478 if (clientlist.size() >= MAXCLIENTS)
1480 kill_link(clientlist[tempnick],"No more connections allowed");
1484 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1485 // its a pretty big but for the moment valid assumption:
1486 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1487 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1488 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1489 // which for the time being is a physical impossibility (even the largest networks dont have more
1490 // than about 10,000 users on ONE server!)
1491 if ((unsigned)socket > 65534)
1493 kill_link(clientlist[tempnick],"Server is full");
1498 char* e = matches_exception(ip);
1501 char* r = matches_zline(ip);
1504 char reason[MAXBUF];
1505 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1506 kill_link(clientlist[tempnick],reason);
1510 fd_ref_table[socket] = clientlist[tempnick];
1511 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1514 /* shows the message of the day, and any other on-logon stuff */
1515 void FullConnectUser(userrec* user)
1518 user->idle_lastmsg = TIME;
1519 log(DEBUG,"ConnectUser: %s",user->nick);
1521 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1523 kill_link(user,"Invalid password");
1528 kill_link(user,"Unauthorised connection");
1532 char match_against[MAXBUF];
1533 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1534 char* e = matches_exception(match_against);
1537 char* r = matches_gline(match_against);
1540 char reason[MAXBUF];
1541 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1542 kill_link_silent(user,reason);
1545 r = matches_kline(user->host);
1548 char reason[MAXBUF];
1549 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1550 kill_link_silent(user,reason);
1556 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1557 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1558 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1559 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1560 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1561 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1562 std::stringstream v;
1563 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1564 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1565 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1567 std::string data005 = v.str();
1568 FOREACH_MOD On005Numeric(data005);
1569 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1570 // so i'd better split it :)
1571 std::stringstream out(data005);
1572 std::string token = "";
1573 std::string line5 = "";
1574 int token_counter = 0;
1578 line5 = line5 + token + " ";
1580 if ((token_counter >= 13) || (out.eof() == true))
1582 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1589 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1590 // onto the network and produce 'fake direction'
1591 FOREACH_MOD OnUserConnect(user);
1592 FOREACH_MOD OnGlobalConnect(user);
1593 user->registered = 7;
1594 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1598 /* shows the message of the day, and any other on-logon stuff */
1599 void ConnectUser(userrec *user)
1601 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1602 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1604 FullConnectUser(user);
1608 std::string GetVersionString()
1610 char Revision[] = "$Revision$";
1611 char versiondata[MAXBUF];
1612 char *s1 = Revision;
1614 char *v2 = strtok_r(s1," ",&savept);
1616 v2 = strtok_r(s1," ",&savept);
1619 char dnsengine[] = "multithread";
1621 char dnsengine[] = "singlethread";
1623 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1627 void handle_version(char **parameters, int pcnt, userrec *user)
1629 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1633 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1635 for (unsigned int i = 0; i < cmdlist.size(); i++)
1637 if (!strcasecmp(cmdlist[i].command,commandname))
1639 if (cmdlist[i].handler_function)
1641 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1643 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1645 if (cmdlist[i].flags_needed)
1647 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1665 // calls a handler function for a command
1667 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1669 for (unsigned int i = 0; i < cmdlist.size(); i++)
1671 if (!strcasecmp(cmdlist[i].command,commandname))
1673 if (cmdlist[i].handler_function)
1675 if (pcnt>=cmdlist[i].min_params)
1677 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1679 if (cmdlist[i].flags_needed)
1681 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1683 cmdlist[i].handler_function(parameters,pcnt,user);
1688 cmdlist[i].handler_function(parameters,pcnt,user);
1698 void force_nickchange(userrec* user,const char* newnick)
1705 FOREACH_RESULT(OnUserPreNick(user,newnick));
1708 kill_link(user,"Nickname collision");
1711 if (matches_qline(newnick))
1714 kill_link(user,"Nickname collision");
1722 strncpy(nick,newnick,MAXBUF);
1724 if (user->registered == 7)
1728 handle_nick(pars,1,user);
1734 int process_parameters(char **command_p,char *parameters)
1737 int q = strlen(parameters);
1740 /* no parameters, command_p invalid! */
1743 if (parameters[0] == ':')
1745 command_p[0] = parameters+1;
1750 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1752 /* only one parameter */
1753 command_p[0] = parameters;
1754 if (parameters[0] == ':')
1756 if (strchr(parameters,' ') != NULL)
1764 command_p[j++] = parameters;
1765 for (int i = 0; i <= q; i++)
1767 if (parameters[i] == ' ')
1769 command_p[j++] = parameters+i+1;
1770 parameters[i] = '\0';
1771 if (command_p[j-1][0] == ':')
1773 *command_p[j-1]++; /* remove dodgy ":" */
1775 /* parameter like this marks end of the sequence */
1779 return j; /* returns total number of items in the list */
1782 void process_command(userrec *user, char* cmd)
1786 char *command_p[127];
1787 char p[MAXBUF], temp[MAXBUF];
1788 int j, items, cmd_found;
1790 for (int i = 0; i < 127; i++)
1791 command_p[i] = NULL;
1806 int total_params = 0;
1809 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1811 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1814 // found a 'trailing', we dont count them after this.
1822 // another phidjit bug...
1823 if (total_params > 126)
1825 *(strchr(cmd,' ')) = '\0';
1826 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1830 strlcpy(temp,cmd,MAXBUF);
1832 std::string tmp = cmd;
1833 for (int i = 0; i <= MODCOUNT; i++)
1835 std::string oldtmp = tmp;
1836 modules[i]->OnServerRaw(tmp,true,user);
1839 log(DEBUG,"A Module changed the input string!");
1840 log(DEBUG,"New string: %s",tmp.c_str());
1841 log(DEBUG,"Old string: %s",oldtmp.c_str());
1845 strlcpy(cmd,tmp.c_str(),MAXBUF);
1846 strlcpy(temp,cmd,MAXBUF);
1848 if (!strchr(cmd,' '))
1850 /* no parameters, lets skip the formalities and not chop up
1852 log(DEBUG,"About to preprocess command with no params");
1854 command_p[0] = NULL;
1856 for (unsigned int i = 0; i <= strlen(cmd); i++)
1858 cmd[i] = toupper(cmd[i]);
1866 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1867 for (unsigned int i = 0; i < strlen(temp); i++)
1869 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1875 /* split the full string into a command plus parameters */
1879 if (strchr(cmd,' '))
1881 for (unsigned int i = 0; i <= strlen(cmd); i++)
1883 /* capitalise the command ONLY, leave params intact */
1884 cmd[i] = toupper(cmd[i]);
1885 /* are we nearly there yet?! :P */
1889 parameters = cmd+i+1;
1897 for (unsigned int i = 0; i <= strlen(cmd); i++)
1899 cmd[i] = toupper(cmd[i]);
1906 if (strlen(command)>MAXCOMMAND)
1908 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1912 for (unsigned int x = 0; x < strlen(command); x++)
1914 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1916 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1918 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1921 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1928 for (unsigned int i = 0; i != cmdlist.size(); i++)
1930 if (cmdlist[i].command[0])
1932 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1938 items = process_parameters(command_p,parameters);
1943 command_p[0] = NULL;
1949 command_p[0] = NULL;
1954 /* activity resets the ping pending timer */
1955 user->nping = TIME + user->pingmax;
1956 if ((items) < cmdlist[i].min_params)
1958 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1959 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1962 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1964 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1965 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1969 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1971 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1972 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1976 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1978 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1980 if ((!isnick(user->nick)) || (user->registered != 7))
1982 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1983 WriteServ(user->fd,"451 %s :You have not registered",command);
1987 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1989 std::stringstream dcmds(DisabledCommands);
1990 while (!dcmds.eof())
1992 std::string thiscmd;
1994 if (!strcasecmp(thiscmd.c_str(),command))
1996 // command is disabled!
1997 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2002 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2004 if (cmdlist[i].handler_function)
2007 /* ikky /stats counters */
2010 cmdlist[i].use_count++;
2011 cmdlist[i].total_bytes+=strlen(temp);
2015 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2016 if (MOD_RESULT == 1) {
2020 /* WARNING: nothing may come after the
2021 * command handler call, as the handler
2022 * may free the user structure! */
2024 cmdlist[i].handler_function(command_p,items,user);
2030 WriteServ(user->fd,"451 %s :You have not registered",command);
2038 if ((!cmd_found) && (user))
2041 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2045 bool removecommands(const char* source)
2047 bool go_again = true;
2051 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2053 if (!strcmp(i->source,source))
2055 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2066 void process_buffer(const char* cmdbuf,userrec *user)
2070 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2076 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2083 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2085 strlcpy(cmd,cmdbuf,MAXBUF);
2090 int sl = strlen(cmd)-1;
2091 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2096 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2101 while (cmd[sl] == ' ') // strip trailing spaces
2111 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2113 if ((user) && (cmd))
2115 process_command(user,cmd);
2119 char MODERR[MAXBUF];
2126 void erase_factory(int j)
2129 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2134 factory.push_back(NULL);
2141 void erase_module(int j)
2144 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2150 modules.push_back(NULL);
2156 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2160 module_names.erase(v);
2168 bool UnloadModule(const char* filename)
2170 std::string filename_str = filename;
2171 for (unsigned int j = 0; j != module_names.size(); j++)
2173 if (module_names[j] == filename_str)
2175 if (modules[j]->GetVersion().Flags & VF_STATIC)
2177 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2178 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2181 /* Give the module a chance to tidy out all its metadata */
2182 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2184 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2186 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2188 modules[j]->OnCleanup(TYPE_USER,u->second);
2190 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2192 log(DEBUG,"Deleting module...");
2194 log(DEBUG,"Erasing module entry...");
2196 log(DEBUG,"Removing dependent commands...");
2197 removecommands(filename);
2198 log(DEFAULT,"Module %s unloaded",filename);
2203 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2204 snprintf(MODERR,MAXBUF,"Module not loaded");
2208 bool LoadModule(const char* filename)
2210 char modfile[MAXBUF];
2212 snprintf(modfile,MAXBUF,"%s",filename);
2214 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2216 std::string filename_str = filename;
2218 if (!DirValid(modfile))
2220 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2221 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2225 log(DEBUG,"Loading module: %s",modfile);
2227 if (FileExists(modfile))
2230 for (unsigned int j = 0; j < module_names.size(); j++)
2232 if (module_names[j] == filename_str)
2234 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2235 snprintf(MODERR,MAXBUF,"Module already loaded");
2239 ircd_module* a = new ircd_module(modfile);
2240 factory[MODCOUNT+1] = a;
2241 if (factory[MODCOUNT+1]->LastError())
2243 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2244 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2248 if (factory[MODCOUNT+1]->factory)
2250 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2251 modules[MODCOUNT+1] = m;
2252 /* save the module and the module's classfactory, if
2253 * this isnt done, random crashes can occur :/ */
2254 module_names.push_back(filename);
2258 log(DEFAULT,"Unable to load %s",modfile);
2259 snprintf(MODERR,MAXBUF,"Factory function failed!");
2266 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2267 snprintf(MODERR,MAXBUF,"Module file could not be found");
2272 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2278 int clientportcount = 0;
2279 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2281 ConfValue("bind","port",count,configToken,&config_f);
2282 ConfValue("bind","address",count,Addr,&config_f);
2283 ConfValue("bind","type",count,Type,&config_f);
2284 if (strcmp(Type,"servers"))
2286 // modules handle server bind types now,
2287 // its not a typo in the strcmp.
2288 ports[clientportcount] = atoi(configToken);
2289 strlcpy(addrs[clientportcount],Addr,256);
2291 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2294 portCount = clientportcount;
2296 for (int count = 0; count < portCount; count++)
2298 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2300 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2303 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2305 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2307 else /* well we at least bound to one socket so we'll continue */
2313 /* if we didn't bind to anything then abort */
2314 if (!boundPortCount)
2316 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2317 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2321 return boundPortCount;
2324 int InspIRCd(char** argv, int argc)
2326 bool expire_run = false;
2327 std::vector<int> activefds;
2330 InspSocket* s = NULL;
2331 InspSocket* s_del = NULL;
2332 char target[MAXBUF];
2333 unsigned int numberactive;
2335 /* Beta 7 moved all this stuff out of the main function
2336 * into smaller sub-functions, much tidier -- Brain
2338 OpenLog(argv, argc);
2340 SetupCommandTable();
2341 ReadConfig(true,NULL);
2342 AddServerName(ServerName);
2344 boundPortCount = BindPorts();
2347 startup_time = time(NULL);
2350 ConfValue("pid","file",0,PID,&config_f);
2351 // write once here, to try it out and make sure its ok
2356 if (DaemonSeed() == ERROR)
2358 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2363 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2364 * initialize the socket engine.
2366 SE = new SocketEngine();
2368 /* We must load the modules AFTER initializing the socket engine, now */
2371 printf("\nInspIRCd is now running!\n");
2374 freopen("/dev/null","w",stdout);
2375 freopen("/dev/null","w",stderr);
2378 /* Add the listening sockets used for client inbound connections
2379 * to the socket engine
2381 for (int count = 0; count < portCount; count++)
2382 SE->AddFd(openSockfd[count],true,X_LISTEN);
2386 /* main loop, this never returns */
2389 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2390 * Once per loop iteration is pleanty.
2395 /* Run background module timers every few seconds
2396 * (the docs say modules shouldnt rely on accurate
2397 * timing using this event, so we dont have to
2398 * time this exactly).
2400 if (((TIME % 8) == 0) && (!expire_run))
2403 FOREACH_MOD OnBackgroundTimer(TIME);
2407 if ((TIME % 8) == 1)
2410 /* Once a second, do the background processing */
2411 if (TIME != OLDTIME)
2412 while (DoBackgroundUserStuff(TIME));
2414 /* Call the socket engine to wait on the active
2415 * file descriptors. The socket engine has everything's
2416 * descriptors in its list... dns, modules, users,
2417 * servers... so its nice and easy, just one call.
2419 SE->Wait(activefds);
2422 * Now process each of the fd's. For users, we have a fast
2423 * lookup table which can find a user by file descriptor, so
2424 * processing them by fd isnt expensive. If we have a lot of
2425 * listening ports or module sockets though, things could get
2428 numberactive = activefds.size();
2429 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2431 int socket_type = SE->GetType(activefds[activefd]);
2432 switch (socket_type)
2434 case X_ESTAB_CLIENT:
2436 cu = fd_ref_table[activefds[activefd]];
2442 case X_ESTAB_MODULE:
2444 /* Process module-owned sockets.
2445 * Modules are encouraged to inherit their sockets from
2446 * InspSocket so we can process them neatly like this.
2448 s = socket_ref[activefds[activefd]];
2450 if ((s) && (!s->Poll()))
2452 log(DEBUG,"Socket poll returned false, close and bail");
2453 SE->DelFd(s->GetFd());
2454 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2456 s_del = (InspSocket*)*a;
2457 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2459 module_sockets.erase(a);
2471 /* When we are using single-threaded dns,
2472 * the sockets for dns end up in our mainloop.
2473 * When we are using multi-threaded dns,
2474 * each thread has its own basic poll() loop
2475 * within it, making them 'fire and forget'
2476 * and independent of the mainloop.
2478 log(DEBUG,"Got a ready socket of type X_ESTAB_DNS");
2479 #ifndef THREADED_DNS
2480 dns_poll(activefds[activefd]);
2486 /* It's a listener */
2487 for (int count = 0; count < boundPortCount; count++)
2489 if (activefds[activefd] == openSockfd[count])
2491 length = sizeof (client);
2492 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2493 log(DEBUG,"Accepted socket %d",incomingSockfd);
2494 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2495 /* Years and years ago, we used to resolve here
2496 * using gethostbyaddr(). That is sucky and we
2497 * don't do that any more...
2499 if (incomingSockfd >= 0)
2501 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, ports[count]);
2503 AddClient(incomingSockfd, target, ports[count], false, inet_ntoa (client.sin_addr));
2504 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2508 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)ports[count],target);
2509 log(DEBUG,"accept failed: %lu",(unsigned long)ports[count]);
2512 /* We've found out what port it belongs on,
2513 * no need to iterate the rest
2521 /* Something went wrong if we're in here.
2522 * In fact, so wrong, im not quite sure
2523 * what we would do, so for now, its going
2524 * to safely do bugger all.
2531 /* This is never reached -- we hope! */