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>
32 #include <sys/types.h>
33 #include <sys/event.h>
38 #include <sys/epoll.h>
45 #include <ext/hash_map>
67 #include "inspstring.h"
69 #include "helperfuncs.h"
71 #include "socketengine.h"
75 int LogLevel = DEFAULT;
76 char ServerName[MAXBUF];
78 char ServerDesc[MAXBUF];
79 char AdminName[MAXBUF];
80 char AdminEmail[MAXBUF];
81 char AdminNick[MAXBUF];
83 char restartpass[MAXBUF];
87 char PrefixQuit[MAXBUF];
88 char DieValue[MAXBUF];
89 char DNSServer[MAXBUF];
92 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
93 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
95 time_t startup_time = time(NULL);
96 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
97 int MaxConn = SOMAXCONN; // size of accept() backlog (128 by default on *BSD)
98 unsigned int SoftLimit = MAXCLIENTS;
99 extern int MaxWhoResults;
103 char DisabledCommands[MAXBUF];
105 bool AllowHalfop = true;
106 bool AllowProtect = true;
107 bool AllowFounder = true;
109 extern std::vector<Module*> modules;
110 std::vector<std::string> module_names;
111 extern std::vector<ircd_module*> factory;
113 std::vector<InspSocket*> module_sockets;
116 int openSockfd[MAXSOCKS];
118 bool unlimitcore = false;
119 struct sockaddr_in client,server;
120 char addrs[MAXBUF][255];
122 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
124 extern InspSocket* socket_ref[65535];
126 time_t TIME = time(NULL), OLDTIME = time(NULL);
128 SocketEngine* SE = NULL;
130 bool has_been_netsplit = false;
131 extern std::vector<std::string> include_stack;
133 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
134 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
135 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
136 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
137 typedef std::deque<command_t> command_table;
138 typedef std::map<std::string,time_t> autoconnects;
139 typedef std::vector<std::string> servernamelist;
141 // This table references users by file descriptor.
142 // its an array to make it VERY fast, as all lookups are referenced
143 // by an integer, meaning there is no need for a scan/search operation.
144 userrec* fd_ref_table[65536];
146 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
148 Server* MyServer = new Server;
152 user_hash clientlist;
155 command_table cmdlist;
156 autoconnects autoconns;
162 servernamelist servernames;
164 struct linger linger = { 0 };
165 char MyExecutable[1024];
166 int boundPortCount = 0;
167 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
169 char ModPath[MAXBUF];
173 int has_channel(userrec *u, chanrec *c);
174 int usercount(chanrec *c);
175 int usercount_i(chanrec *c);
176 char* Passwd(userrec *user);
177 bool IsDenied(userrec *user);
178 void AddWhoWas(userrec* u);
180 std::stringstream config_f(stringstream::in | stringstream::out);
182 std::vector<userrec*> all_opers;
186 void AddOper(userrec* user)
188 log(DEBUG,"Oper added to optimization list");
189 all_opers.push_back(user);
192 void AddServerName(std::string servername)
194 log(DEBUG,"Adding server name: %s",servername.c_str());
195 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
197 if (*a == servername)
200 servernames.push_back(servername);
203 const char* FindServerNamePtr(std::string servername)
205 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
207 if (*a == servername)
210 AddServerName(servername);
211 return FindServerNamePtr(servername);
214 void DeleteOper(userrec* user)
216 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
220 log(DEBUG,"Oper removed from optimization list");
227 std::string GetRevision()
229 char Revision[] = "$Revision$";
232 char *v2 = strtok_r(s1," ",&savept);
234 v2 = strtok_r(s1," ",&savept);
236 return std::string(v2);
240 std::string getservername()
245 std::string getserverdesc()
250 std::string getnetworkname()
255 std::string getadminname()
260 std::string getadminemail()
265 std::string getadminnick()
270 void ReadConfig(bool bail, userrec* user)
272 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
273 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
275 std::stringstream errstr;
276 include_stack.clear();
278 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
281 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
284 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
292 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
293 while (!errstr.eof())
295 errstr.getline(dataline,1024);
296 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
301 WriteOpers("There were errors in the configuration file:");
302 while (!errstr.eof())
304 errstr.getline(dataline,1024);
305 WriteOpers(dataline);
312 ConfValue("server","name",0,ServerName,&config_f);
313 ConfValue("server","description",0,ServerDesc,&config_f);
314 ConfValue("server","network",0,Network,&config_f);
315 ConfValue("admin","name",0,AdminName,&config_f);
316 ConfValue("admin","email",0,AdminEmail,&config_f);
317 ConfValue("admin","nick",0,AdminNick,&config_f);
318 ConfValue("files","motd",0,motd,&config_f);
319 ConfValue("files","rules",0,rules,&config_f);
320 ConfValue("power","diepass",0,diepass,&config_f);
321 ConfValue("power","pause",0,pauseval,&config_f);
322 ConfValue("power","restartpass",0,restartpass,&config_f);
323 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
324 ConfValue("die","value",0,DieValue,&config_f);
325 ConfValue("options","loglevel",0,dbg,&config_f);
326 ConfValue("options","netbuffersize",0,NB,&config_f);
327 ConfValue("options","maxwho",0,MW,&config_f);
328 ConfValue("options","allowhalfop",0,AH,&config_f);
329 ConfValue("options","allowprotect",0,AP,&config_f);
330 ConfValue("options","allowfounder",0,AF,&config_f);
331 ConfValue("dns","server",0,DNSServer,&config_f);
332 ConfValue("dns","timeout",0,DNT,&config_f);
333 ConfValue("options","moduledir",0,ModPath,&config_f);
334 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
335 ConfValue("options","somaxconn",0,MCON,&config_f);
336 ConfValue("options","softlimit",0,SLIMT,&config_f);
338 SoftLimit = atoi(SLIMT);
339 if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
341 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
342 SoftLimit = MAXCLIENTS;
344 MaxConn = atoi(MCON);
345 if (MaxConn > SOMAXCONN)
346 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
347 NetBufferSize = atoi(NB);
348 MaxWhoResults = atoi(MW);
349 dns_timeout = atoi(DNT);
355 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
357 strlcpy(ModPath,MOD_PATH,MAXBUF);
358 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
359 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
360 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
361 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
363 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
364 NetBufferSize = 10240;
366 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
368 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
371 if (!strcmp(dbg,"debug"))
373 if (!strcmp(dbg,"verbose"))
375 if (!strcmp(dbg,"default"))
377 if (!strcmp(dbg,"sparse"))
379 if (!strcmp(dbg,"none"))
382 log(DEFAULT,"Reading message of the day...");
383 readfile(RULES,rules);
384 log(DEFAULT,"Reading connect classes...");
386 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
389 ConfValue("connect","allow",i,Value,&config_f);
390 ConfValue("connect","timeout",i,timeout,&config_f);
391 ConfValue("connect","flood",i,flood,&config_f);
392 ConfValue("connect","pingfreq",i,pfreq,&config_f);
393 ConfValue("connect","threshold",i,thold,&config_f);
394 ConfValue("connect","sendq",i,sqmax,&config_f);
395 ConfValue("connect","recvq",i,rqmax,&config_f);
398 strlcpy(c.host,Value,MAXBUF);
400 strlcpy(Value,"",MAXBUF);
401 ConfValue("connect","password",i,Value,&config_f);
402 strlcpy(c.pass,Value,MAXBUF);
403 c.registration_timeout = 90; // default is 2 minutes
405 c.flood = atoi(flood);
407 c.sendqmax = 262144; // 256k
408 c.recvqmax = 4096; // 4k
411 c.threshold = atoi(thold);
415 c.sendqmax = atoi(sqmax);
419 c.recvqmax = atoi(rqmax);
423 c.registration_timeout = atoi(timeout);
427 c.pingtime = atoi(pfreq);
429 Classes.push_back(c);
430 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);
434 ConfValue("connect","deny",i,Value,&config_f);
435 strlcpy(c.host,Value,MAXBUF);
437 Classes.push_back(c);
438 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
442 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
443 read_xline_defaults();
444 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
448 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
450 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
451 ConfValue("link","name",i,Link_ServerName,&config_f);
452 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
453 if (strcmp(Link_AConn,""))
455 autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
460 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
463 log(DEFAULT,"Adding and removing modules due to rehash...");
465 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
467 // store the old module names
468 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
470 old_module_names.push_back(*t);
473 // get the new module names
474 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
476 ConfValue("module","name",count2,Value,&config_f);
477 new_module_names.push_back(Value);
480 // now create a list of new modules that are due to be loaded
481 // and a seperate list of modules which are due to be unloaded
482 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
485 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
491 added_modules.push_back(*_new);
493 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
496 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
502 removed_modules.push_back(*oldm);
504 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
506 int rem = 0, add = 0;
507 if (!removed_modules.empty())
508 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
510 if (UnloadModule(removing->c_str()))
512 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
513 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
518 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
521 if (!added_modules.empty())
522 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
524 if (LoadModule(adding->c_str()))
526 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
527 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
532 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
535 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());
540 /* add a channel to a user, creating the record for it if needed and linking
541 * it to the user record */
543 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
545 if ((!user) || (!cn))
547 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
555 strncpy(cname,cn,MAXBUF);
557 // we MUST declare this wherever we use FOREACH_RESULT
560 if (strlen(cname) > CHANMAX)
562 cname[CHANMAX] = '\0';
565 log(DEBUG,"add_channel: %s %s",user->nick,cname);
567 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
569 return NULL; // already on the channel!
573 if (!FindChan(cname))
575 if (!strcasecmp(ServerName,user->server))
578 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
579 if (MOD_RESULT == 1) {
584 /* create a new one */
585 log(DEBUG,"add_channel: creating: %s",cname);
587 chanlist[cname] = new chanrec();
589 strlcpy(chanlist[cname]->name, cname,CHANMAX);
590 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
591 chanlist[cname]->created = TIME;
592 strcpy(chanlist[cname]->topic, "");
593 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
594 chanlist[cname]->topicset = 0;
595 Ptr = chanlist[cname];
596 log(DEBUG,"add_channel: created: %s",cname);
597 /* set created to 2 to indicate user
598 * is the first in the channel
599 * and should be given ops */
605 /* channel exists, just fish out a pointer to its struct */
606 Ptr = FindChan(cname);
609 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
611 // remote users are allowed us to bypass channel modes
612 // and bans (used by servers)
613 if (!strcasecmp(ServerName,user->server))
615 log(DEBUG,"Not overriding...");
617 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
618 if (MOD_RESULT == 1) {
621 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
625 log(DEBUG,"add_channel: checking key, invite, etc");
627 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
632 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
635 log(DEBUG,"add_channel: no key given in JOIN");
636 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
641 if (strcasecmp(key,Ptr->key))
643 log(DEBUG,"add_channel: bad key given in JOIN");
644 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
649 log(DEBUG,"add_channel: no key");
652 FOREACH_RESULT(OnCheckInvite(user, Ptr));
655 if (Ptr->binarymodes & CM_INVITEONLY)
657 log(DEBUG,"add_channel: channel is +i");
658 if (user->IsInvited(Ptr->name))
660 /* user was invited to channel */
661 /* there may be an optional channel NOTICE here */
665 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
669 log(DEBUG,"add_channel: channel is not +i");
672 FOREACH_RESULT(OnCheckLimit(user, Ptr));
677 if (usercount(Ptr) >= Ptr->limit)
679 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
684 log(DEBUG,"add_channel: about to walk banlist");
686 FOREACH_RESULT(OnCheckBan(user, Ptr));
689 /* check user against the channel banlist */
692 if (Ptr->bans.size())
694 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
696 if (match(user->GetFullHost(),i->data))
698 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
704 log(DEBUG,"add_channel: bans checked");
712 user->RemoveInvite(Ptr->name);
715 log(DEBUG,"add_channel: invites removed");
720 log(DEBUG,"Overridden checks");
728 log(DEBUG,"Passed channel checks");
730 for (int index =0; index != MAXCHANS; index++)
732 log(DEBUG,"Check location %d",index);
733 if (user->chans[index].channel == NULL)
735 log(DEBUG,"Adding into their channel list at location %d",index);
739 /* first user in is given ops */
740 user->chans[index].uc_modes = UCMODE_OP;
744 user->chans[index].uc_modes = 0;
746 user->chans[index].channel = Ptr;
747 Ptr->AddUser((char*)user);
748 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
750 log(DEBUG,"Sent JOIN to client");
754 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
755 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
758 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
759 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
760 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
761 FOREACH_MOD OnUserJoin(user,Ptr);
765 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
766 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
770 /* remove a channel from a users record, and remove the record from memory
771 * if the channel has become empty */
773 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
775 if ((!user) || (!cname))
777 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
783 if ((!cname) || (!user))
788 Ptr = FindChan(cname);
795 FOREACH_MOD OnUserPart(user,Ptr);
796 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
798 for (int i =0; i != MAXCHANS; i++)
800 /* zap it from the channel list of the user */
801 if (user->chans[i].channel == Ptr)
805 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
809 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
811 user->chans[i].uc_modes = 0;
812 user->chans[i].channel = NULL;
813 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
818 Ptr->DelUser((char*)user);
820 /* if there are no users left on the channel */
823 chan_hash::iterator iter = chanlist.find(Ptr->name);
825 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
827 /* kill the record */
828 if (iter != chanlist.end())
830 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
832 chanlist.erase(iter);
840 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
842 if ((!src) || (!user) || (!Ptr) || (!reason))
844 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
848 if ((!Ptr) || (!user) || (!src))
853 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
855 if (!has_channel(user,Ptr))
857 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
862 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
863 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
866 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
868 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
870 if (cstatus(src,Ptr) == STATUS_HOP)
872 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
876 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
883 if (!is_uline(src->server))
886 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
891 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
893 for (int i =0; i != MAXCHANS; i++)
895 /* zap it from the channel list of the user */
896 if (user->chans[i].channel)
897 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
899 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
900 user->chans[i].uc_modes = 0;
901 user->chans[i].channel = NULL;
902 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
907 Ptr->DelUser((char*)user);
909 /* if there are no users left on the channel */
912 chan_hash::iterator iter = chanlist.find(Ptr->name);
914 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
916 /* kill the record */
917 if (iter != chanlist.end())
919 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
921 chanlist.erase(iter);
929 /* This function pokes and hacks at a parameter list like the following:
931 * PART #winbot,#darkgalaxy :m00!
933 * to turn it into a series of individual calls like this:
936 * PART #darkgalaxy :m00!
938 * The seperate calls are sent to a callback function provided by the caller
939 * (the caller will usually call itself recursively). The callback function
940 * must be a command handler. Calling this function on a line with no list causes
941 * no action to be taken. You must provide a starting and ending parameter number
942 * where the range of the list can be found, useful if you have a terminating
943 * parameter as above which is actually not part of the list, or parameters
944 * before the actual list as well. This code is used by many functions which
945 * can function as "one to list" (see the RFC) */
947 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
952 char blog[32][MAXBUF];
953 char blog2[32][MAXBUF];
954 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
958 for (int i = 0; i <32; i++)
961 for (int i = 0; i <32; i++)
965 for (int i = 0; i <10; i++)
974 if (pcnt > 1) /* we have a key to copy */
976 strlcpy(keystr,parameters[1],MAXBUF);
980 if (!parameters[start])
984 if (!strchr(parameters[start],','))
989 for (int i = start; i <= end; i++)
993 strlcat(plist,parameters[i],MAXBUF);
1001 for (int i = 0; i < t; i++)
1003 if (plist[i] == ',')
1006 strlcpy(blog[j++],param,MAXBUF);
1010 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1015 strlcpy(blog[j++],param,MAXBUF);
1018 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1023 if ((joins) && (keystr))
1025 if (strchr(keystr,','))
1029 t2 = strlen(keystr);
1030 for (int i = 0; i < t2; i++)
1032 if (keystr[i] == ',')
1035 strlcpy(blog2[j++],param,MAXBUF);
1039 strlcpy(blog2[j++],param,MAXBUF);
1044 for (j = 0; j < total; j++)
1050 for (q = end; q < pcnt-1; q++)
1052 if (parameters[q+1])
1054 pars[q-end+1] = parameters[q+1];
1057 if ((joins) && (parameters[1]))
1068 /* repeatedly call the function with the hacked parameter list */
1069 if ((joins) && (pcnt > 1))
1073 // pars[1] already set up and containing key from blog2[j]
1078 pars[1] = parameters[1];
1084 fn(pars,pcnt-(end-start),u);
1093 void kill_link(userrec *user,const char* r)
1095 user_hash::iterator iter = clientlist.find(user->nick);
1097 char reason[MAXBUF];
1099 strncpy(reason,r,MAXBUF);
1101 if (strlen(reason)>MAXQUIT)
1103 reason[MAXQUIT-1] = '\0';
1106 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1107 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1108 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1110 if (user->registered == 7) {
1111 FOREACH_MOD OnUserQuit(user,reason);
1112 WriteCommonExcept(user,"QUIT :%s",reason);
1115 user->FlushWriteBuf();
1117 FOREACH_MOD OnUserDisconnect(user);
1121 FOREACH_MOD OnRawSocketClose(user->fd);
1122 SE->DelFd(user->fd);
1123 user->CloseSocket();
1126 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1127 // if they were an oper with +s.
1128 if (user->registered == 7) {
1129 purge_empty_chans(user);
1130 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1131 if (!strcmp(user->server,ServerName))
1132 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1136 if (iter != clientlist.end())
1138 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1140 fd_ref_table[user->fd] = NULL;
1141 clientlist.erase(iter);
1146 void kill_link_silent(userrec *user,const char* r)
1148 user_hash::iterator iter = clientlist.find(user->nick);
1150 char reason[MAXBUF];
1152 strncpy(reason,r,MAXBUF);
1154 if (strlen(reason)>MAXQUIT)
1156 reason[MAXQUIT-1] = '\0';
1159 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1160 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1161 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1163 user->FlushWriteBuf();
1165 if (user->registered == 7) {
1166 FOREACH_MOD OnUserQuit(user,reason);
1167 WriteCommonExcept(user,"QUIT :%s",reason);
1170 FOREACH_MOD OnUserDisconnect(user);
1174 FOREACH_MOD OnRawSocketClose(user->fd);
1175 SE->DelFd(user->fd);
1176 user->CloseSocket();
1179 if (user->registered == 7) {
1180 purge_empty_chans(user);
1183 if (iter != clientlist.end())
1185 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1187 fd_ref_table[user->fd] = NULL;
1188 clientlist.erase(iter);
1194 /*void *task(void *arg)
1197 cout << (char *)arg;
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;
1466 for (int i = 0; i < MAXCHANS; i++)
1468 clientlist[tempnick]->chans[i].channel = NULL;
1469 clientlist[tempnick]->chans[i].uc_modes = 0;
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);
1513 // initialize their dns lookup thread
1514 //if (pthread_create(&clientlist[tempnick]->dnsthread, NULL, dns_task, (void *)clientlist[tempnick]) != 0)
1516 // log(DEBUG,"Failed to create DNS lookup thread for user %s",clientlist[tempnick]->nick);
1520 /* shows the message of the day, and any other on-logon stuff */
1521 void FullConnectUser(userrec* user)
1524 user->idle_lastmsg = TIME;
1525 log(DEBUG,"ConnectUser: %s",user->nick);
1527 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1529 kill_link(user,"Invalid password");
1534 kill_link(user,"Unauthorised connection");
1538 char match_against[MAXBUF];
1539 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1540 char* e = matches_exception(match_against);
1543 char* r = matches_gline(match_against);
1546 char reason[MAXBUF];
1547 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1548 kill_link_silent(user,reason);
1551 r = matches_kline(user->host);
1554 char reason[MAXBUF];
1555 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1556 kill_link_silent(user,reason);
1562 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1563 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1564 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1565 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1566 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1567 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1568 std::stringstream v;
1569 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1570 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1571 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1573 std::string data005 = v.str();
1574 FOREACH_MOD On005Numeric(data005);
1575 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1576 // so i'd better split it :)
1577 std::stringstream out(data005);
1578 std::string token = "";
1579 std::string line5 = "";
1580 int token_counter = 0;
1584 line5 = line5 + token + " ";
1586 if ((token_counter >= 13) || (out.eof() == true))
1588 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1595 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1596 // onto the network and produce 'fake direction'
1597 FOREACH_MOD OnUserConnect(user);
1598 FOREACH_MOD OnGlobalConnect(user);
1599 user->registered = 7;
1600 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1604 /* shows the message of the day, and any other on-logon stuff */
1605 void ConnectUser(userrec *user)
1607 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1608 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1610 FullConnectUser(user);
1614 std::string GetVersionString()
1616 char Revision[] = "$Revision$";
1617 char versiondata[MAXBUF];
1618 char *s1 = Revision;
1620 char *v2 = strtok_r(s1," ",&savept);
1622 v2 = strtok_r(s1," ",&savept);
1625 char dnsengine[] = "multithread";
1627 char dnsengine[] = "singlethread";
1629 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1633 void handle_version(char **parameters, int pcnt, userrec *user)
1635 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1639 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1641 for (unsigned int i = 0; i < cmdlist.size(); i++)
1643 if (!strcasecmp(cmdlist[i].command,commandname))
1645 if (cmdlist[i].handler_function)
1647 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1649 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1651 if (cmdlist[i].flags_needed)
1653 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1671 // calls a handler function for a command
1673 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1675 for (unsigned int i = 0; i < cmdlist.size(); i++)
1677 if (!strcasecmp(cmdlist[i].command,commandname))
1679 if (cmdlist[i].handler_function)
1681 if (pcnt>=cmdlist[i].min_params)
1683 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1685 if (cmdlist[i].flags_needed)
1687 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1689 cmdlist[i].handler_function(parameters,pcnt,user);
1694 cmdlist[i].handler_function(parameters,pcnt,user);
1704 void force_nickchange(userrec* user,const char* newnick)
1711 FOREACH_RESULT(OnUserPreNick(user,newnick));
1714 kill_link(user,"Nickname collision");
1717 if (matches_qline(newnick))
1720 kill_link(user,"Nickname collision");
1728 strncpy(nick,newnick,MAXBUF);
1730 if (user->registered == 7)
1734 handle_nick(pars,1,user);
1740 int process_parameters(char **command_p,char *parameters)
1743 int q = strlen(parameters);
1746 /* no parameters, command_p invalid! */
1749 if (parameters[0] == ':')
1751 command_p[0] = parameters+1;
1756 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1758 /* only one parameter */
1759 command_p[0] = parameters;
1760 if (parameters[0] == ':')
1762 if (strchr(parameters,' ') != NULL)
1770 command_p[j++] = parameters;
1771 for (int i = 0; i <= q; i++)
1773 if (parameters[i] == ' ')
1775 command_p[j++] = parameters+i+1;
1776 parameters[i] = '\0';
1777 if (command_p[j-1][0] == ':')
1779 *command_p[j-1]++; /* remove dodgy ":" */
1781 /* parameter like this marks end of the sequence */
1785 return j; /* returns total number of items in the list */
1788 void process_command(userrec *user, char* cmd)
1792 char *command_p[127];
1793 char p[MAXBUF], temp[MAXBUF];
1794 int j, items, cmd_found;
1796 for (int i = 0; i < 127; i++)
1797 command_p[i] = NULL;
1812 int total_params = 0;
1815 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1817 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1820 // found a 'trailing', we dont count them after this.
1828 // another phidjit bug...
1829 if (total_params > 126)
1831 *(strchr(cmd,' ')) = '\0';
1832 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1836 strlcpy(temp,cmd,MAXBUF);
1838 std::string tmp = cmd;
1839 for (int i = 0; i <= MODCOUNT; i++)
1841 std::string oldtmp = tmp;
1842 modules[i]->OnServerRaw(tmp,true,user);
1845 log(DEBUG,"A Module changed the input string!");
1846 log(DEBUG,"New string: %s",tmp.c_str());
1847 log(DEBUG,"Old string: %s",oldtmp.c_str());
1851 strlcpy(cmd,tmp.c_str(),MAXBUF);
1852 strlcpy(temp,cmd,MAXBUF);
1854 if (!strchr(cmd,' '))
1856 /* no parameters, lets skip the formalities and not chop up
1858 log(DEBUG,"About to preprocess command with no params");
1860 command_p[0] = NULL;
1862 for (unsigned int i = 0; i <= strlen(cmd); i++)
1864 cmd[i] = toupper(cmd[i]);
1872 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1873 for (unsigned int i = 0; i < strlen(temp); i++)
1875 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1881 /* split the full string into a command plus parameters */
1885 if (strchr(cmd,' '))
1887 for (unsigned int i = 0; i <= strlen(cmd); i++)
1889 /* capitalise the command ONLY, leave params intact */
1890 cmd[i] = toupper(cmd[i]);
1891 /* are we nearly there yet?! :P */
1895 parameters = cmd+i+1;
1903 for (unsigned int i = 0; i <= strlen(cmd); i++)
1905 cmd[i] = toupper(cmd[i]);
1912 if (strlen(command)>MAXCOMMAND)
1914 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1918 for (unsigned int x = 0; x < strlen(command); x++)
1920 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1922 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1924 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1927 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1934 for (unsigned int i = 0; i != cmdlist.size(); i++)
1936 if (cmdlist[i].command[0])
1938 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1944 items = process_parameters(command_p,parameters);
1949 command_p[0] = NULL;
1955 command_p[0] = NULL;
1960 /* activity resets the ping pending timer */
1961 user->nping = TIME + user->pingmax;
1962 if ((items) < cmdlist[i].min_params)
1964 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1965 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1968 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1970 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1971 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1975 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1977 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1978 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1982 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1984 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1986 if ((!isnick(user->nick)) || (user->registered != 7))
1988 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1989 WriteServ(user->fd,"451 %s :You have not registered",command);
1993 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1995 std::stringstream dcmds(DisabledCommands);
1996 while (!dcmds.eof())
1998 std::string thiscmd;
2000 if (!strcasecmp(thiscmd.c_str(),command))
2002 // command is disabled!
2003 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2008 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2010 if (cmdlist[i].handler_function)
2013 /* ikky /stats counters */
2016 cmdlist[i].use_count++;
2017 cmdlist[i].total_bytes+=strlen(temp);
2021 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2022 if (MOD_RESULT == 1) {
2026 /* WARNING: nothing may come after the
2027 * command handler call, as the handler
2028 * may free the user structure! */
2030 cmdlist[i].handler_function(command_p,items,user);
2036 WriteServ(user->fd,"451 %s :You have not registered",command);
2044 if ((!cmd_found) && (user))
2047 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2051 bool removecommands(const char* source)
2053 bool go_again = true;
2057 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2059 if (!strcmp(i->source,source))
2061 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2072 void process_buffer(const char* cmdbuf,userrec *user)
2076 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2082 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2089 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2091 strlcpy(cmd,cmdbuf,MAXBUF);
2096 int sl = strlen(cmd)-1;
2097 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2102 if ((cmd[sl] == 13) || (cmd[sl] == 10))
2107 while (cmd[sl] == ' ') // strip trailing spaces
2117 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2119 if ((user) && (cmd))
2121 process_command(user,cmd);
2125 char MODERR[MAXBUF];
2132 void erase_factory(int j)
2135 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2140 factory.push_back(NULL);
2147 void erase_module(int j)
2150 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2156 modules.push_back(NULL);
2162 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2166 module_names.erase(v);
2174 bool UnloadModule(const char* filename)
2176 std::string filename_str = filename;
2177 for (unsigned int j = 0; j != module_names.size(); j++)
2179 if (module_names[j] == filename_str)
2181 if (modules[j]->GetVersion().Flags & VF_STATIC)
2183 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2184 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2187 /* Give the module a chance to tidy out all its metadata */
2188 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2190 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2192 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2194 modules[j]->OnCleanup(TYPE_USER,u->second);
2196 FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2198 log(DEBUG,"Deleting module...");
2200 log(DEBUG,"Erasing module entry...");
2202 log(DEBUG,"Removing dependent commands...");
2203 removecommands(filename);
2204 log(DEFAULT,"Module %s unloaded",filename);
2209 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2210 snprintf(MODERR,MAXBUF,"Module not loaded");
2214 bool LoadModule(const char* filename)
2216 char modfile[MAXBUF];
2218 snprintf(modfile,MAXBUF,"%s",filename);
2220 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2222 std::string filename_str = filename;
2224 if (!DirValid(modfile))
2226 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2227 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2231 log(DEBUG,"Loading module: %s",modfile);
2233 if (FileExists(modfile))
2236 for (unsigned int j = 0; j < module_names.size(); j++)
2238 if (module_names[j] == filename_str)
2240 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2241 snprintf(MODERR,MAXBUF,"Module already loaded");
2245 ircd_module* a = new ircd_module(modfile);
2246 factory[MODCOUNT+1] = a;
2247 if (factory[MODCOUNT+1]->LastError())
2249 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2250 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2254 if (factory[MODCOUNT+1]->factory)
2256 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2257 modules[MODCOUNT+1] = m;
2258 /* save the module and the module's classfactory, if
2259 * this isnt done, random crashes can occur :/ */
2260 module_names.push_back(filename);
2264 log(DEFAULT,"Unable to load %s",modfile);
2265 snprintf(MODERR,MAXBUF,"Factory function failed!");
2272 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2273 snprintf(MODERR,MAXBUF,"Module file could not be found");
2278 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2283 void ProcessUser(userrec* cu)
2285 int result = EAGAIN;
2286 log(DEBUG,"Processing user with fd %d",cu->fd);
2289 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
2292 result = cu->ReadData(data, 65535);
2296 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
2299 log(DEBUG,"Read result: %d",result);
2302 statsRecv += result;
2303 // perform a check on the raw buffer as an array (not a string!) to remove
2304 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
2305 // hopefully this should stop even more people whining about "Unknown command: *"
2306 for (int checker = 0; checker < result; checker++)
2308 if ((data[checker] == 0) || (data[checker] == 7))
2309 data[checker] = ' ';
2312 data[result] = '\0';
2313 userrec* current = cu;
2314 int currfd = current->fd;
2316 // add the data to the users buffer
2319 if (!current->AddBuffer(data))
2321 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
2322 if (current->registered == 7)
2324 kill_link(current,"RecvQ exceeded");
2328 WriteOpers("*** Excess flood from %s",current->ip);
2329 log(DEFAULT,"Excess flood from: %s",current->ip);
2330 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2335 if (current->recvq.length() > (unsigned)NetBufferSize)
2337 if (current->registered == 7)
2339 kill_link(current,"RecvQ exceeded");
2343 WriteOpers("*** Excess flood from %s",current->ip);
2344 log(DEFAULT,"Excess flood from: %s",current->ip);
2345 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2350 // while there are complete lines to process...
2351 while (current->BufferIsReady())
2354 if (TIME > current->reset_due)
2356 current->reset_due = TIME + current->threshold;
2357 current->lines_in = 0;
2359 current->lines_in++;
2360 if (current->lines_in > current->flood)
2362 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2363 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2364 kill_link(current,"Excess flood");
2367 if ((floodlines > current->flood) && (current->flood != 0))
2369 if (current->registered == 7)
2371 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2372 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2373 kill_link(current,"Excess flood");
2377 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
2382 char sanitized[MAXBUF];
2383 // use GetBuffer to copy single lines into the sanitized string
2384 std::string single_line = current->GetBuffer();
2385 current->bytes_in += single_line.length();
2387 if (single_line.length()>512)
2389 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2390 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
2391 kill_link(current,"Excess flood");
2394 strlcpy(sanitized,single_line.c_str(),MAXBUF);
2397 userrec* old_comp = fd_ref_table[currfd];
2398 // we're gonna re-scan to check if the nick is gone, after every
2399 // command - if it has, we're gonna bail
2400 process_buffer(sanitized,current);
2401 // look for the user's record in case it's changed... if theyve quit,
2402 // we cant do anything more with their buffer, so bail.
2403 // there used to be an ugly, slow loop here. Now we have a reference
2404 // table, life is much easier (and FASTER)
2405 userrec* new_comp = fd_ref_table[currfd];
2406 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
2412 /* The user is still here, flush their buffer */
2413 current->FlushWriteBuf();
2419 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
2421 log(DEBUG,"killing: %s",cu->nick);
2422 kill_link(cu,strerror(errno));
2426 // result EAGAIN means nothing read
2427 else if (result == EAGAIN)
2430 else if (result == 0)
2432 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
2433 kill_link(cu,"Client exited");
2434 log(DEBUG,"Bailing from client exit");
2440 * This function is called once a second from the mainloop.
2441 * It is intended to do background checking on all the user structs, e.g.
2442 * stuff like ping checks, registration timeouts, etc.
2443 * The function returns false when it is finished, and true if
2444 * it needs to be run again (e.g. it has processed one of a batch of
2445 * QUIT messages, but couldnt continue iterating because the iterator
2446 * became invalid). This function is also responsible for checking
2447 * if InspSocket derived classes are timed out.
2449 bool DoBackgroundUserStuff(time_t TIME)
2451 unsigned int numsockets = module_sockets.size();
2452 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2454 InspSocket* s = (InspSocket*)*a;
2455 if (s->Timeout(TIME))
2457 log(DEBUG,"Socket poll returned false, close and bail");
2458 SE->DelFd(s->GetFd());
2460 module_sockets.erase(a);
2464 if (module_sockets.size() != numsockets) break;
2466 /* TODO: We need a seperate hash containing only local users for this
2468 for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
2470 /* Sanity checks for corrupted iterators (yes, really) */
2471 userrec* curr = NULL;
2473 curr = count2->second;
2474 if ((long)curr == -1)
2477 if ((curr) && (curr->fd != 0))
2479 int currfd = curr->fd;
2480 // we don't check the state of remote users.
2481 if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2483 curr->FlushWriteBuf();
2484 if (curr->GetWriteError() != "")
2486 log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2487 kill_link(curr,curr->GetWriteError().c_str());
2490 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2491 // their connection class.
2492 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
2494 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2495 kill_link(curr,"Registration timeout");
2498 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2500 log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
2501 curr->dns_done = true;
2503 FullConnectUser(curr);
2504 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2507 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2509 log(DEBUG,"dns done, registered=3, and modules ready, OK");
2510 FullConnectUser(curr);
2511 if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2514 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
2516 if ((!curr->lastping) && (curr->registered == 7))
2518 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
2519 kill_link(curr,"Ping timeout");
2522 Write(curr->fd,"PING :%s",ServerName);
2523 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
2525 curr->nping = TIME+curr->pingmax; // was hard coded to 120
2533 void OpenLog(char** argv, int argc)
2535 std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2536 log_file = fopen(logpath.c_str(),"a+");
2539 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2543 printf("Logging to ircd.log...\n");
2545 printf("Logging to %s...\n",logpath.c_str());
2554 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2555 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2563 int clientportcount = 0;
2564 for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2566 ConfValue("bind","port",count,configToken,&config_f);
2567 ConfValue("bind","address",count,Addr,&config_f);
2568 ConfValue("bind","type",count,Type,&config_f);
2569 if (strcmp(Type,"servers"))
2571 // modules handle server bind types now,
2572 // its not a typo in the strcmp.
2573 ports[clientportcount] = atoi(configToken);
2574 strlcpy(addrs[clientportcount],Addr,256);
2576 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2579 portCount = clientportcount;
2581 for (int count = 0; count < portCount; count++)
2583 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2585 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2588 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2590 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2592 else /* well we at least bound to one socket so we'll continue */
2598 /* if we didn't bind to anything then abort */
2599 if (!boundPortCount)
2601 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2602 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2606 return boundPortCount;
2613 printf("WARNING: %s\n\n",DieValue);
2614 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2619 void LoadAllModules()
2621 /* We must load the modules AFTER initializing the socket engine, now */
2623 for (int count = 0; count < ConfValueEnum("module",&config_f); count++)
2625 ConfValue("module","name",count,configToken,&config_f);
2626 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2627 if (!LoadModule(configToken))
2629 log(DEFAULT,"Exiting due to a module loader error.");
2630 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2634 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2637 int InspIRCd(char** argv, int argc)
2639 bool expire_run = false;
2640 std::vector<int> activefds;
2643 InspSocket* s = NULL;
2644 InspSocket* s_del = NULL;
2645 char target[MAXBUF];
2646 unsigned int numberactive;
2648 /* Beta 7 moved all this stuff out of the main function
2649 * into smaller sub-functions, much tidier -- Brain
2651 OpenLog(argv, argc);
2653 SetupCommandTable();
2654 ReadConfig(true,NULL);
2655 AddServerName(ServerName);
2657 boundPortCount = BindPorts();
2660 startup_time = time(NULL);
2663 ConfValue("pid","file",0,PID,&config_f);
2664 // write once here, to try it out and make sure its ok
2669 if (DaemonSeed() == ERROR)
2671 printf("ERROR: could not go into daemon mode. Shutting down.\n");
2676 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2677 * initialize the socket engine.
2679 SE = new SocketEngine();
2681 /* We must load the modules AFTER initializing the socket engine, now */
2684 printf("\nInspIRCd is now running!\n");
2687 freopen("/dev/null","w",stdout);
2688 freopen("/dev/null","w",stderr);
2691 /* Add the listening sockets used for client inbound connections
2692 * to the socket engine
2694 for (int count = 0; count < portCount; count++)
2695 SE->AddFd(openSockfd[count],true,X_LISTEN);
2699 /* main loop, this never returns */
2702 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2703 * Once per loop iteration is pleanty.
2708 /* Run background module timers every few seconds
2709 * (the docs say modules shouldnt rely on accurate
2710 * timing using this event, so we dont have to
2711 * time this exactly).
2713 if (((TIME % 8) == 0) && (!expire_run))
2716 FOREACH_MOD OnBackgroundTimer(TIME);
2720 if ((TIME % 8) == 1)
2723 /* Once a second, do the background processing */
2724 if (TIME != OLDTIME)
2725 while (DoBackgroundUserStuff(TIME));
2727 /* Call the socket engine to wait on the active
2728 * file descriptors. The socket engine has everything's
2729 * descriptors in its list... dns, modules, users,
2730 * servers... so its nice and easy, just one call.
2732 SE->Wait(activefds);
2735 * Now process each of the fd's. For users, we have a fast
2736 * lookup table which can find a user by file descriptor, so
2737 * processing them by fd isnt expensive. If we have a lot of
2738 * listening ports or module sockets though, things could get
2741 numberactive = activefds.size();
2742 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2744 int socket_type = SE->GetType(activefds[activefd]);
2745 switch (socket_type)
2747 case X_ESTAB_CLIENT:
2749 cu = fd_ref_table[activefds[activefd]];
2755 case X_ESTAB_MODULE:
2757 /* Process module-owned sockets.
2758 * Modules are encouraged to inherit their sockets from
2759 * InspSocket so we can process them neatly like this.
2761 s = socket_ref[activefds[activefd]];
2763 if ((s) && (!s->Poll()))
2765 log(DEBUG,"Socket poll returned false, close and bail");
2766 SE->DelFd(s->GetFd());
2767 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2769 s_del = (InspSocket*)*a;
2770 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2772 module_sockets.erase(a);
2784 /* When we are using single-threaded dns,
2785 * the sockets for dns end up in our mainloop.
2786 * When we are using multi-threaded dns,
2787 * each thread has its own basic poll() loop
2788 * within it, making them 'fire and forget'
2789 * and independent of the mainloop.
2791 log(DEBUG,"Got a ready socket of type X_ESTAB_DNS");
2792 #ifndef THREADED_DNS
2793 dns_poll(activefds[activefd]);
2799 /* It's a listener */
2800 for (int count = 0; count < boundPortCount; count++)
2802 if (activefds[activefd] == openSockfd[count])
2804 length = sizeof (client);
2805 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2806 log(DEBUG,"Accepted socket %d",incomingSockfd);
2807 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2808 /* Years and years ago, we used to resolve here
2809 * using gethostbyaddr(). That is sucky and we
2810 * don't do that any more...
2812 if (incomingSockfd >= 0)
2814 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, ports[count]);
2816 AddClient(incomingSockfd, target, ports[count], false, inet_ntoa (client.sin_addr));
2817 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2821 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)ports[count],target);
2822 log(DEBUG,"accept failed: %lu",(unsigned long)ports[count]);
2825 /* We've found out what port it belongs on,
2826 * no need to iterate the rest
2834 /* Something went wrong if we're in here.
2835 * In fact, so wrong, im not quite sure
2836 * what we would do, so for now, its going
2837 * to safely do bugger all.
2844 /* This is never reached -- we hope! */