1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 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! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
46 #include "connection.h"
58 #include "inspstring.h"
62 #define nspace __gnu_cxx
67 int LogLevel = DEFAULT;
68 char ServerName[MAXBUF];
70 char ServerDesc[MAXBUF];
71 char AdminName[MAXBUF];
72 char AdminEmail[MAXBUF];
73 char AdminNick[MAXBUF];
75 char restartpass[MAXBUF];
79 char PrefixQuit[MAXBUF];
80 char DieValue[MAXBUF];
81 char DNSServer[MAXBUF];
83 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
84 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
86 time_t startup_time = time(NULL);
87 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
88 extern int MaxWhoResults;
92 bool AllowHalfop = true;
93 bool AllowProtect = true;
94 bool AllowFounder = true;
96 extern std::vector<Module*> modules;
97 std::vector<std::string> module_names;
98 extern std::vector<ircd_module*> factory;
99 std::vector<int> fd_reap;
102 int openSockfd[MAXSOCKS];
105 time_t TIME = time(NULL);
110 template<> struct hash<in_addr>
112 template<> struct nspace::hash<in_addr>
115 size_t operator()(const struct in_addr &a) const
118 memcpy(&q,&a,sizeof(size_t));
123 template<> struct hash<string>
125 template<> struct nspace::hash<string>
128 size_t operator()(const string &s) const
131 static struct hash<const char *> strhash;
132 strlcpy(a,s.c_str(),MAXBUF);
143 bool operator()(const string& s1, const string& s2) const
145 char a[MAXBUF],b[MAXBUF];
146 strlcpy(a,s1.c_str(),MAXBUF);
147 strlcpy(b,s2.c_str(),MAXBUF);
148 return (strcasecmp(a,b) == 0);
153 struct InAddr_HashComp
156 bool operator()(const in_addr &s1, const in_addr &s2) const
161 memcpy(&q,&s1,sizeof(size_t));
162 memcpy(&p,&s2,sizeof(size_t));
170 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
171 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
172 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
173 typedef std::deque<command_t> command_table;
179 user_hash clientlist;
182 command_table cmdlist;
189 struct linger linger = { 0 };
190 char MyExecutable[1024];
191 int boundPortCount = 0;
192 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
193 int defaultRoute = 0;
194 char ModPath[MAXBUF];
198 long MyKey = C.GenKey();
202 int has_channel(userrec *u, chanrec *c);
203 int usercount(chanrec *c);
204 int usercount_i(chanrec *c);
205 char* Passwd(userrec *user);
206 bool IsDenied(userrec *user);
207 void AddWhoWas(userrec* u);
209 std::vector<long> auth_cookies;
210 std::stringstream config_f(stringstream::in | stringstream::out);
216 char Revision[] = "$Revision$";
219 char *v1 = strtok_r(s1," ",&savept);
221 char *v2 = strtok_r(s1," ",&savept);
223 return (long)(atof(v2)*10000);
227 std::string getservername()
232 std::string getserverdesc()
237 std::string getnetworkname()
242 std::string getadminname()
247 std::string getadminemail()
252 std::string getadminnick()
257 void log(int level,char *text, ...)
259 char textbuffer[MAXBUF];
262 struct tm * timeinfo;
263 if (level < LogLevel)
267 timeinfo = localtime (&rawtime);
272 va_start (argsPtr, text);
273 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
275 strlcpy(b,asctime(timeinfo),MAXBUF);
276 b[strlen(b)-1] = ':';
277 fprintf(log_file,"%s %s\n",b,textbuffer);
280 // nofork enabled? display it on terminal too
281 printf("%s %s\n",b,textbuffer);
286 void readfile(file_cache &F, const char* fname)
289 char linebuf[MAXBUF];
291 log(DEBUG,"readfile: loading %s",fname);
293 file = fopen(fname,"r");
298 fgets(linebuf,sizeof(linebuf),file);
299 linebuf[strlen(linebuf)-1]='\0';
300 if (!strcmp(linebuf,""))
306 F.push_back(linebuf);
313 log(DEBUG,"readfile: failed to load file: %s",fname);
315 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
318 void ReadConfig(bool bail, userrec* user)
320 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
321 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF];
323 std::stringstream errstr;
325 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
330 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
338 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
339 while (!errstr.eof())
341 errstr.getline(dataline,1024);
342 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
347 WriteOpers("There were errors in the configuration file:",user->nick);
348 while (!errstr.eof())
350 errstr.getline(dataline,1024);
351 WriteOpers(dataline);
358 ConfValue("server","name",0,ServerName,&config_f);
359 ConfValue("server","description",0,ServerDesc,&config_f);
360 ConfValue("server","network",0,Network,&config_f);
361 ConfValue("admin","name",0,AdminName,&config_f);
362 ConfValue("admin","email",0,AdminEmail,&config_f);
363 ConfValue("admin","nick",0,AdminNick,&config_f);
364 ConfValue("files","motd",0,motd,&config_f);
365 ConfValue("files","rules",0,rules,&config_f);
366 ConfValue("power","diepass",0,diepass,&config_f);
367 ConfValue("power","pause",0,pauseval,&config_f);
368 ConfValue("power","restartpass",0,restartpass,&config_f);
369 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
370 ConfValue("die","value",0,DieValue,&config_f);
371 ConfValue("options","loglevel",0,dbg,&config_f);
372 ConfValue("options","netbuffersize",0,NB,&config_f);
373 ConfValue("options","maxwho",0,MW,&config_f);
374 ConfValue("options","allowhalfop",0,AH,&config_f);
375 ConfValue("options","allowprotect",0,AP,&config_f);
376 ConfValue("options","allowfounder",0,AF,&config_f);
377 ConfValue("dns","server",0,DNSServer,&config_f);
378 ConfValue("dns","timeout",0,DNT,&config_f);
379 ConfValue("options","moduledir",0,ModPath,&config_f);
380 NetBufferSize = atoi(NB);
381 MaxWhoResults = atoi(MW);
382 dns_timeout = atoi(DNT);
385 if (!strcmp(DNSServer,""))
386 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
387 if (!strcmp(ModPath,""))
388 strlcpy(ModPath,MOD_PATH,MAXBUF);
389 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
390 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
391 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
392 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
394 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
395 NetBufferSize = 10240;
397 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
399 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
402 if (!strcmp(dbg,"debug"))
404 if (!strcmp(dbg,"verbose"))
406 if (!strcmp(dbg,"default"))
408 if (!strcmp(dbg,"sparse"))
410 if (!strcmp(dbg,"none"))
413 log(DEFAULT,"Reading message of the day...");
414 readfile(RULES,rules);
415 log(DEFAULT,"Reading connect classes...");
417 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
420 ConfValue("connect","allow",i,Value,&config_f);
421 ConfValue("connect","timeout",i,timeout,&config_f);
422 ConfValue("connect","flood",i,flood,&config_f);
423 ConfValue("connect","pingfreq",i,pfreq,&config_f);
424 if (strcmp(Value,""))
426 strlcpy(c.host,Value,MAXBUF);
428 strlcpy(Value,"",MAXBUF);
429 ConfValue("connect","password",i,Value,&config_f);
430 strlcpy(c.pass,Value,MAXBUF);
431 c.registration_timeout = 90; // default is 2 minutes
433 c.flood = atoi(flood);
436 c.registration_timeout = atoi(timeout);
440 c.pingtime = atoi(pfreq);
442 Classes.push_back(c);
443 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
447 ConfValue("connect","deny",i,Value,&config_f);
448 strlcpy(c.host,Value,MAXBUF);
450 Classes.push_back(c);
451 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
455 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
456 read_xline_defaults();
457 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
459 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
462 log(DEFAULT,"Adding and removing modules due to rehash...");
464 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
466 // store the old module names
467 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
469 old_module_names.push_back(*t);
472 // get the new module names
473 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
475 ConfValue("module","name",count2,Value,&config_f);
476 new_module_names.push_back(Value);
479 // now create a list of new modules that are due to be loaded
480 // and a seperate list of modules which are due to be unloaded
481 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
484 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
490 added_modules.push_back(*_new);
492 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
495 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
501 removed_modules.push_back(*oldm);
503 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
505 int rem = 0, add = 0;
506 if (!removed_modules.empty())
507 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
509 if (UnloadModule(removing->c_str()))
511 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
512 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
517 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
520 if (!added_modules.empty())
521 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
523 if (LoadModule(adding->c_str()))
525 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
526 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
531 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
534 log(DEFAULT,"Successfully unloaded %d of %d modules and loaded %d of %d modules.",rem,removed_modules.size(),add,added_modules.size());
538 /* write formatted text to a socket, in same format as printf */
540 void Write(int sock,char *text, ...)
544 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
547 char textbuffer[MAXBUF];
551 va_start (argsPtr, text);
552 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
554 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
558 write(sock,tb,strlen(tb));
562 /* write a server formatted numeric response to a single socket */
564 void WriteServ(int sock, char* text, ...)
568 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
571 char textbuffer[MAXBUF],tb[MAXBUF];
573 va_start (argsPtr, text);
575 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
577 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
581 write(sock,tb,strlen(tb));
585 /* write text from an originating user to originating user */
587 void WriteFrom(int sock, userrec *user,char* text, ...)
589 if ((!text) || (!user))
591 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
594 char textbuffer[MAXBUF],tb[MAXBUF];
596 va_start (argsPtr, text);
598 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
600 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
604 write(sock,tb,strlen(tb));
608 /* write text to an destination user from a source user (e.g. user privmsg) */
610 void WriteTo(userrec *source, userrec *dest,char *data, ...)
612 if ((!dest) || (!data))
614 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
617 char textbuffer[MAXBUF],tb[MAXBUF];
619 va_start (argsPtr, data);
620 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
624 // if no source given send it from the server.
627 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
631 WriteFrom(dest->fd,source,"%s",textbuffer);
635 /* write formatted text from a source user to all users on a channel
636 * including the sender (NOT for privmsg, notice etc!) */
638 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
640 if ((!Ptr) || (!user) || (!text))
642 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
645 char textbuffer[MAXBUF];
647 va_start (argsPtr, text);
648 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
650 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
652 if (has_channel(i->second,Ptr))
654 WriteTo(user,i->second,"%s",textbuffer);
659 /* write formatted text from a source user to all users on a channel
660 * including the sender (NOT for privmsg, notice etc!) doesnt send to
661 * users on remote servers */
663 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
665 if ((!Ptr) || (!text))
667 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
670 char textbuffer[MAXBUF];
672 va_start (argsPtr, text);
673 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
675 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
677 if (has_channel(i->second,Ptr))
679 if (i->second->fd != -1)
683 WriteServ(i->second->fd,"%s",textbuffer);
687 WriteTo(user,i->second,"%s",textbuffer);
695 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
697 if ((!Ptr) || (!user) || (!text))
699 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
702 char textbuffer[MAXBUF];
704 va_start (argsPtr, text);
705 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
707 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
711 if (has_channel(i->second,Ptr))
713 WriteServ(i->second->fd,"%s",textbuffer);
720 /* write formatted text from a source user to all users on a channel except
721 * for the sender (for privmsg etc) */
723 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
725 if ((!Ptr) || (!user) || (!text))
727 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
730 char textbuffer[MAXBUF];
732 va_start (argsPtr, text);
733 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
736 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
740 if (has_channel(i->second,Ptr) && (user != i->second))
742 WriteTo(user,i->second,"%s",textbuffer);
749 std::string GetServerDescription(char* servername)
751 for (int j = 0; j < 32; j++)
755 for (int k = 0; k < me[j]->connectors.size(); k++)
757 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
759 return me[j]->connectors[k].GetDescription();
763 return ServerDesc; // not a remote server that can be found, it must be me.
768 /* write a formatted string to all users who share at least one common
769 * channel, including the source user e.g. for use in NICK */
771 void WriteCommon(userrec *u, char* text, ...)
775 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
779 if (u->registered != 7) {
780 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
784 char textbuffer[MAXBUF];
786 va_start (argsPtr, text);
787 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
790 WriteFrom(u->fd,u,"%s",textbuffer);
792 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
796 if (common_channels(u,i->second) && (i->second != u))
798 WriteFrom(i->second->fd,u,"%s",textbuffer);
804 /* write a formatted string to all users who share at least one common
805 * channel, NOT including the source user e.g. for use in QUIT */
807 void WriteCommonExcept(userrec *u, char* text, ...)
811 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
815 if (u->registered != 7) {
816 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
820 char textbuffer[MAXBUF];
822 va_start (argsPtr, text);
823 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
826 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
830 if ((common_channels(u,i->second)) && (u != i->second))
832 WriteFrom(i->second->fd,u,"%s",textbuffer);
838 void WriteOpers(char* text, ...)
842 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
846 char textbuffer[MAXBUF];
848 va_start (argsPtr, text);
849 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
852 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
856 if (strchr(i->second->modes,'o'))
858 if (strchr(i->second->modes,'s'))
860 // send server notices to all with +s
861 // (TODO: needs SNOMASKs)
862 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
869 // returns TRUE of any users on channel C occupy server 'servername'.
871 bool ChanAnyOnThisServer(chanrec *c,char* servername)
873 log(DEBUG,"ChanAnyOnThisServer");
874 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
876 if (has_channel(i->second,c))
878 if (!strcasecmp(i->second->server,servername))
887 // returns true if user 'u' shares any common channels with any users on server 'servername'
889 bool CommonOnThisServer(userrec* u,const char* servername)
891 log(DEBUG,"ChanAnyOnThisServer");
892 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
894 if ((common_channels(u,i->second)) && (u != i->second))
896 if (!strcasecmp(i->second->server,servername))
898 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
907 void NetSendToCommon(userrec* u, char* s)
910 snprintf(buffer,MAXBUF,"%s",s);
912 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
914 for (int j = 0; j < 32; j++)
918 for (int k = 0; k < me[j]->connectors.size(); k++)
920 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
922 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
930 void NetSendToAll(char* s)
933 snprintf(buffer,MAXBUF,"%s",s);
935 log(DEBUG,"NetSendToAll: '%s'",s);
937 for (int j = 0; j < 32; j++)
941 for (int k = 0; k < me[j]->connectors.size(); k++)
943 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
949 void NetSendToAllAlive(char* s)
952 snprintf(buffer,MAXBUF,"%s",s);
954 log(DEBUG,"NetSendToAllAlive: '%s'",s);
956 for (int j = 0; j < 32; j++)
960 for (int k = 0; k < me[j]->connectors.size(); k++)
962 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
964 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
968 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
976 void NetSendToOne(char* target,char* s)
979 snprintf(buffer,MAXBUF,"%s",s);
981 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
983 for (int j = 0; j < 32; j++)
987 for (int k = 0; k < me[j]->connectors.size(); k++)
989 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
991 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
998 void NetSendToAllExcept(const char* target,char* s)
1000 char buffer[MAXBUF];
1001 snprintf(buffer,MAXBUF,"%s",s);
1003 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
1005 for (int j = 0; j < 32; j++)
1009 for (int k = 0; k < me[j]->connectors.size(); k++)
1011 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1013 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1021 void WriteMode(const char* modes, int flags, const char* text, ...)
1023 if ((!text) || (!modes) || (!flags))
1025 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1029 char textbuffer[MAXBUF];
1031 va_start (argsPtr, text);
1032 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1035 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1039 bool send_to_user = false;
1041 if (flags == WM_AND)
1043 send_to_user = true;
1044 for (int n = 0; n < strlen(modes); n++)
1046 if (!hasumode(i->second,modes[n]))
1048 send_to_user = false;
1053 else if (flags == WM_OR)
1055 send_to_user = false;
1056 for (int n = 0; n < strlen(modes); n++)
1058 if (hasumode(i->second,modes[n]))
1060 send_to_user = true;
1068 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1075 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1077 if ((!text) || (!source))
1079 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1084 char textbuffer[MAXBUF];
1086 va_start (argsPtr, text);
1087 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1090 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1094 if (strchr(i->second->modes,'w'))
1096 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1103 char buffer[MAXBUF];
1104 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1105 NetSendToAll(buffer);
1109 /* convert a string to lowercase. Note following special circumstances
1110 * taken from RFC 1459. Many "official" server branches still hold to this
1111 * rule so i will too;
1113 * Because of IRC's scandanavian origin, the characters {}| are
1114 * considered to be the lower case equivalents of the characters []\,
1115 * respectively. This is a critical issue when determining the
1116 * equivalence of two nicknames.
1119 void strlower(char *n)
1125 for (int i = 0; i != strlen(n); i++)
1127 n[i] = tolower(n[i]);
1139 /* Find a user record by nickname and return a pointer to it */
1141 userrec* Find(std::string nick)
1143 user_hash::iterator iter = clientlist.find(nick);
1145 if (iter == clientlist.end())
1146 /* Couldn't find it */
1149 return iter->second;
1152 /* find a channel record by channel name and return a pointer to it */
1154 chanrec* FindChan(const char* chan)
1158 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1162 chan_hash::iterator iter = chanlist.find(chan);
1164 if (iter == chanlist.end())
1165 /* Couldn't find it */
1168 return iter->second;
1172 long GetMaxBans(char* name)
1175 for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1177 ConfValue("banlist","chan",count,CM,&config_f);
1180 ConfValue("banlist","limit",count,CM,&config_f);
1188 void purge_empty_chans(void)
1190 int go_again = 1, purge = 0;
1195 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1198 if (!usercount(i->second))
1200 /* kill the record */
1201 if (i != chanlist.end())
1203 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1204 if (i->second) delete i->second;
1213 log(DEBUG,"skipped purge for %s",i->second->name);
1218 log(DEBUG,"completed channel purge, killed %d",purge);
1222 char scratch[MAXBUF];
1223 char sparam[MAXBUF];
1225 char* chanmodes(chanrec *chan)
1229 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1236 if (chan->noexternal)
1238 strlcat(scratch,"n",MAXMODES);
1240 if (chan->topiclock)
1242 strlcat(scratch,"t",MAXMODES);
1244 if (strcmp(chan->key,""))
1246 strlcat(scratch,"k",MAXMODES);
1250 strlcat(scratch,"l",MAXMODES);
1252 if (chan->inviteonly)
1254 strlcat(scratch,"i",MAXMODES);
1256 if (chan->moderated)
1258 strlcat(scratch,"m",MAXMODES);
1262 strlcat(scratch,"s",MAXMODES);
1264 if (chan->c_private)
1266 strlcat(scratch,"p",MAXMODES);
1268 if (strcmp(chan->key,""))
1270 strlcat(sparam," ",MAXBUF);
1271 strlcat(sparam,chan->key,MAXBUF);
1276 sprintf(foo," %d",chan->limit);
1277 strlcat(sparam,foo,MAXBUF);
1279 if (strlen(chan->custom_modes))
1281 strlcat(scratch,chan->custom_modes,MAXMODES);
1282 for (int z = 0; z < strlen(chan->custom_modes); z++)
1284 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1287 strlcat(sparam," ",MAXBUF);
1288 strlcat(sparam,extparam.c_str(),MAXBUF);
1292 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1293 strlcat(scratch,sparam,MAXMODES);
1298 /* compile a userlist of a channel into a string, each nick seperated by
1299 * spaces and op, voice etc status shown as @ and + */
1301 void userlist(userrec *user,chanrec *c)
1303 if ((!c) || (!user))
1305 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1309 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1310 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1312 if (has_channel(i->second,c))
1314 if (isnick(i->second->nick))
1316 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1318 /* user is +i, and source not on the channel, does not show
1319 * nick in NAMES list */
1322 strlcat(list,cmode(i->second,c),MAXBUF);
1323 strlcat(list,i->second->nick,MAXBUF);
1324 strlcat(list," ",MAXBUF);
1325 if (strlen(list)>(480-NICKMAX))
1327 /* list overflowed into
1328 * multiple numerics */
1329 WriteServ(user->fd,"%s",list);
1330 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1335 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1337 WriteServ(user->fd,"%s",list);
1341 /* return a count of the users on a specific channel accounting for
1342 * invisible users who won't increase the count. e.g. for /LIST */
1344 int usercount_i(chanrec *c)
1351 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1356 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1360 if (has_channel(i->second,c))
1362 if (isnick(i->second->nick))
1364 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1366 /* user is +i, and source not on the channel, does not show
1367 * nick in NAMES list */
1375 log(DEBUG,"usercount_i: %s %d",c->name,count);
1380 int usercount(chanrec *c)
1387 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1392 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1396 if (has_channel(i->second,c))
1398 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1405 log(DEBUG,"usercount: %s %d",c->name,count);
1410 /* add a channel to a user, creating the record for it if needed and linking
1411 * it to the user record */
1413 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1415 if ((!user) || (!cn))
1417 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1426 strncpy(cname,cn,MAXBUF);
1428 // we MUST declare this wherever we use FOREACH_RESULT
1431 if (strlen(cname) > CHANMAX-1)
1433 cname[CHANMAX-1] = '\0';
1436 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1438 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1440 return NULL; // already on the channel!
1444 if (!FindChan(cname))
1447 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1448 if (MOD_RESULT == 1) {
1452 /* create a new one */
1453 log(DEBUG,"add_channel: creating: %s",cname);
1455 chanlist[cname] = new chanrec();
1457 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1458 chanlist[cname]->topiclock = 1;
1459 chanlist[cname]->noexternal = 1;
1460 chanlist[cname]->created = TIME;
1461 strcpy(chanlist[cname]->topic, "");
1462 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1463 chanlist[cname]->topicset = 0;
1464 Ptr = chanlist[cname];
1465 log(DEBUG,"add_channel: created: %s",cname);
1466 /* set created to 2 to indicate user
1467 * is the first in the channel
1468 * and should be given ops */
1474 /* channel exists, just fish out a pointer to its struct */
1475 Ptr = FindChan(cname);
1478 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1480 // the override flag allows us to bypass channel modes
1481 // and bans (used by servers)
1482 if ((!override) || (!strcasecmp(user->server,ServerName)))
1484 log(DEBUG,"Not overriding...");
1486 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1487 if (MOD_RESULT == 1) {
1490 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1494 log(DEBUG,"add_channel: checking key, invite, etc");
1495 if (strcmp(Ptr->key,""))
1497 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1500 log(DEBUG,"add_channel: no key given in JOIN");
1501 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1506 log(DEBUG,"key at %p is %s",key,key);
1507 if (strcasecmp(key,Ptr->key))
1509 log(DEBUG,"add_channel: bad key given in JOIN");
1510 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1515 log(DEBUG,"add_channel: no key");
1517 if (Ptr->inviteonly)
1519 log(DEBUG,"add_channel: channel is +i");
1520 if (user->IsInvited(Ptr->name))
1522 /* user was invited to channel */
1523 /* there may be an optional channel NOTICE here */
1527 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1531 log(DEBUG,"add_channel: channel is not +i");
1535 if (usercount(Ptr) == Ptr->limit)
1537 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1542 log(DEBUG,"add_channel: about to walk banlist");
1544 /* check user against the channel banlist */
1547 if (Ptr->bans.size())
1549 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1551 if (match(user->GetFullHost(),i->data))
1553 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1560 log(DEBUG,"add_channel: bans checked");
1565 if ((Ptr) && (user))
1567 user->RemoveInvite(Ptr->name);
1570 log(DEBUG,"add_channel: invites removed");
1575 log(DEBUG,"Overridden checks");
1583 log(DEBUG,"Passed channel checks");
1585 for (int i =0; i != MAXCHANS; i++)
1587 log(DEBUG,"Check location %d",i);
1588 if (user->chans[i].channel == NULL)
1590 log(DEBUG,"Adding into their channel list at location %d",i);
1594 /* first user in is given ops */
1595 user->chans[i].uc_modes = UCMODE_OP;
1599 user->chans[i].uc_modes = 0;
1601 user->chans[i].channel = Ptr;
1602 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1604 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1606 // use the stamdard J token with no privilages.
1607 char buffer[MAXBUF];
1610 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1614 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1616 NetSendToAll(buffer);
1619 log(DEBUG,"Sent JOIN to client");
1623 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1624 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1627 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1628 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1629 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1630 FOREACH_MOD OnUserJoin(user,Ptr);
1634 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1635 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1639 /* remove a channel from a users record, and remove the record from memory
1640 * if the channel has become empty */
1642 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1644 if ((!user) || (!cname))
1646 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1653 if ((!cname) || (!user))
1658 Ptr = FindChan(cname);
1665 FOREACH_MOD OnUserPart(user,Ptr);
1666 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1668 for (int i =0; i != MAXCHANS; i++)
1670 /* zap it from the channel list of the user */
1671 if (user->chans[i].channel == Ptr)
1675 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1679 char buffer[MAXBUF];
1680 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1681 NetSendToAll(buffer);
1690 char buffer[MAXBUF];
1691 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1692 NetSendToAll(buffer);
1695 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1697 user->chans[i].uc_modes = 0;
1698 user->chans[i].channel = NULL;
1699 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1704 /* if there are no users left on the channel */
1705 if (!usercount(Ptr))
1707 chan_hash::iterator iter = chanlist.find(Ptr->name);
1709 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1711 /* kill the record */
1712 if (iter != chanlist.end())
1714 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1715 if (iter->second) delete iter->second;
1716 chanlist.erase(iter);
1722 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1724 if ((!src) || (!user) || (!Ptr) || (!reason))
1726 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1733 if ((!Ptr) || (!user) || (!src))
1738 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1740 if (!has_channel(user,Ptr))
1742 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1747 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1749 if (MOD_RESULT == ACR_DENY)
1752 if (MOD_RESULT == ACR_DEFAULT)
1754 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1756 if (cstatus(src,Ptr) == STATUS_HOP)
1758 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1762 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1769 for (int i =0; i != MAXCHANS; i++)
1771 /* zap it from the channel list of the user */
1772 if (user->chans[i].channel)
1773 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1775 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1776 user->chans[i].uc_modes = 0;
1777 user->chans[i].channel = NULL;
1778 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1783 /* if there are no users left on the channel */
1784 if (!usercount(Ptr))
1786 chan_hash::iterator iter = chanlist.find(Ptr->name);
1788 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1790 /* kill the record */
1791 if (iter != chanlist.end())
1793 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1794 if (iter->second) delete iter->second;
1795 chanlist.erase(iter);
1803 /* This function pokes and hacks at a parameter list like the following:
1805 * PART #winbot,#darkgalaxy :m00!
1807 * to turn it into a series of individual calls like this:
1809 * PART #winbot :m00!
1810 * PART #darkgalaxy :m00!
1812 * The seperate calls are sent to a callback function provided by the caller
1813 * (the caller will usually call itself recursively). The callback function
1814 * must be a command handler. Calling this function on a line with no list causes
1815 * no action to be taken. You must provide a starting and ending parameter number
1816 * where the range of the list can be found, useful if you have a terminating
1817 * parameter as above which is actually not part of the list, or parameters
1818 * before the actual list as well. This code is used by many functions which
1819 * can function as "one to list" (see the RFC) */
1821 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1826 char blog[32][MAXBUF];
1827 char blog2[32][MAXBUF];
1828 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1829 char keystr[MAXBUF];
1832 for (int i = 0; i <32; i++)
1835 for (int i = 0; i <32; i++)
1836 strcpy(blog2[i],"");
1839 for (int i = 0; i <10; i++)
1843 parameters[i] = moo;
1848 if (pcnt > 1) /* we have a key to copy */
1850 strlcpy(keystr,parameters[1],MAXBUF);
1854 if (!parameters[start])
1858 if (!strchr(parameters[start],','))
1863 for (int i = start; i <= end; i++)
1867 strlcat(plist,parameters[i],MAXBUF);
1875 for (int i = 0; i < t; i++)
1877 if (plist[i] == ',')
1880 strlcpy(blog[j++],param,MAXBUF);
1884 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1889 strlcpy(blog[j++],param,MAXBUF);
1892 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1897 if ((joins) && (keystr))
1899 if (strchr(keystr,','))
1903 t2 = strlen(keystr);
1904 for (int i = 0; i < t2; i++)
1906 if (keystr[i] == ',')
1909 strlcpy(blog2[j++],param,MAXBUF);
1913 strlcpy(blog2[j++],param,MAXBUF);
1918 for (j = 0; j < total; j++)
1924 for (q = end; q < pcnt-1; q++)
1926 if (parameters[q+1])
1928 pars[q-end+1] = parameters[q+1];
1931 if ((joins) && (parameters[1]))
1942 /* repeatedly call the function with the hacked parameter list */
1943 if ((joins) && (pcnt > 1))
1947 // pars[1] already set up and containing key from blog2[j]
1952 pars[1] = parameters[1];
1958 fn(pars,pcnt-(end-start),u);
1967 void kill_link(userrec *user,const char* r)
1969 user_hash::iterator iter = clientlist.find(user->nick);
1971 char reason[MAXBUF];
1973 strncpy(reason,r,MAXBUF);
1975 if (strlen(reason)>MAXQUIT)
1977 reason[MAXQUIT-1] = '\0';
1980 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1981 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1982 log(DEBUG,"closing fd %d",user->fd);
1984 /* bugfix, cant close() a nonblocking socket (sux!) */
1985 if (user->registered == 7) {
1986 FOREACH_MOD OnUserQuit(user);
1987 WriteCommonExcept(user,"QUIT :%s",reason);
1989 // Q token must go to ALL servers!!!
1990 char buffer[MAXBUF];
1991 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1992 NetSendToAll(buffer);
1995 /* push the socket on a stack of sockets due to be closed at the next opportunity
1996 * 'Client exited' is an exception to this as it means the client side has already
1997 * closed the socket, we don't need to do it.
1999 fd_reap.push_back(user->fd);
2001 bool do_purge = false;
2003 if (user->registered == 7) {
2004 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2008 if (iter != clientlist.end())
2010 log(DEBUG,"deleting user hash value %d",iter->second);
2011 if ((iter->second) && (user->registered == 7)) {
2012 if (iter->second) delete iter->second;
2014 clientlist.erase(iter);
2017 if (user->registered == 7) {
2018 purge_empty_chans();
2023 void kill_link_silent(userrec *user,const char* r)
2025 user_hash::iterator iter = clientlist.find(user->nick);
2027 char reason[MAXBUF];
2029 strncpy(reason,r,MAXBUF);
2031 if (strlen(reason)>MAXQUIT)
2033 reason[MAXQUIT-1] = '\0';
2036 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2037 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2038 log(DEBUG,"closing fd %d",user->fd);
2040 /* bugfix, cant close() a nonblocking socket (sux!) */
2041 if (user->registered == 7) {
2042 FOREACH_MOD OnUserQuit(user);
2043 WriteCommonExcept(user,"QUIT :%s",reason);
2045 // Q token must go to ALL servers!!!
2046 char buffer[MAXBUF];
2047 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2048 NetSendToAll(buffer);
2051 /* push the socket on a stack of sockets due to be closed at the next opportunity
2052 * 'Client exited' is an exception to this as it means the client side has already
2053 * closed the socket, we don't need to do it.
2055 fd_reap.push_back(user->fd);
2057 bool do_purge = false;
2059 if (iter != clientlist.end())
2061 log(DEBUG,"deleting user hash value %d",iter->second);
2062 if ((iter->second) && (user->registered == 7)) {
2063 if (iter->second) delete iter->second;
2065 clientlist.erase(iter);
2068 if (user->registered == 7) {
2069 purge_empty_chans();
2075 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2077 char* Passwd(userrec *user)
2079 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2081 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2089 bool IsDenied(userrec *user)
2091 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2093 if (match(user->host,i->host) && (i->type == CC_DENY))
2104 /* sends out an error notice to all connected clients (not to be used
2107 void send_error(char *s)
2109 log(DEBUG,"send_error: %s",s);
2110 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2112 if (isnick(i->second->nick))
2114 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2118 // fix - unregistered connections receive ERROR, not NOTICE
2119 Write(i->second->fd,"ERROR :%s",s);
2124 void Error(int status)
2126 signal (SIGALRM, SIG_IGN);
2127 signal (SIGPIPE, SIG_IGN);
2128 signal (SIGTERM, SIG_IGN);
2129 signal (SIGABRT, SIG_IGN);
2130 signal (SIGSEGV, SIG_IGN);
2131 signal (SIGURG, SIG_IGN);
2132 signal (SIGKILL, SIG_IGN);
2133 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
2134 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2139 int main(int argc, char **argv)
2143 log(DEBUG,"*** InspIRCd starting up!");
2144 if (!FileExists(CONFIG_FILE))
2146 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2147 log(DEFAULT,"main: no config");
2148 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2152 for (int i = 1; i < argc; i++)
2154 if (!strcmp(argv[i],"-nofork")) {
2157 if (!strcmp(argv[i],"-wait")) {
2162 strlcpy(MyExecutable,argv[0],MAXBUF);
2164 if (InspIRCd() == ERROR)
2166 log(DEFAULT,"main: daemon function bailed");
2167 printf("ERROR: could not initialise. Shutting down.\n");
2174 template<typename T> inline string ConvToStr(const T &in)
2177 if (!(tmp << in)) return string();
2181 /* re-allocates a nick in the user_hash after they change nicknames,
2182 * returns a pointer to the new user as it may have moved */
2184 userrec* ReHashNick(char* Old, char* New)
2186 user_hash::iterator newnick;
2187 user_hash::iterator oldnick = clientlist.find(Old);
2189 log(DEBUG,"ReHashNick: %s %s",Old,New);
2191 if (!strcasecmp(Old,New))
2193 log(DEBUG,"old nick is new nick, skipping");
2194 return oldnick->second;
2197 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2199 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2201 clientlist[New] = new userrec();
2202 clientlist[New] = oldnick->second;
2203 clientlist.erase(oldnick);
2205 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2207 return clientlist[New];
2210 /* adds or updates an entry in the whowas list */
2211 void AddWhoWas(userrec* u)
2213 user_hash::iterator iter = whowas.find(u->nick);
2214 userrec *a = new userrec();
2215 strlcpy(a->nick,u->nick,NICKMAX);
2216 strlcpy(a->ident,u->ident,64);
2217 strlcpy(a->dhost,u->dhost,256);
2218 strlcpy(a->host,u->host,256);
2219 strlcpy(a->fullname,u->fullname,128);
2220 strlcpy(a->server,u->server,256);
2221 a->signon = u->signon;
2223 /* MAX_WHOWAS: max number of /WHOWAS items
2224 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2225 * can be replaced by a newer one
2228 if (iter == whowas.end())
2230 if (whowas.size() == WHOWAS_MAX)
2232 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2234 // 3600 seconds in an hour ;)
2235 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
2237 if (i->second) delete i->second;
2239 log(DEBUG,"added WHOWAS entry, purged an old record");
2246 log(DEBUG,"added fresh WHOWAS entry");
2247 whowas[a->nick] = a;
2252 log(DEBUG,"updated WHOWAS entry");
2253 if (iter->second) delete iter->second;
2259 /* add a client connection to the sockets list */
2260 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2264 char resolved[MAXBUF];
2267 user_hash::iterator iter;
2269 tempnick = ConvToStr(socket) + "-unknown";
2270 sprintf(tn2,"%d-unknown",socket);
2272 iter = clientlist.find(tempnick);
2274 if (iter != clientlist.end()) return;
2277 * It is OK to access the value here this way since we know
2278 * it exists, we just created it above.
2280 * At NO other time should you access a value in a map or a
2281 * hash_map this way.
2283 clientlist[tempnick] = new userrec();
2285 NonBlocking(socket);
2286 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2288 clientlist[tempnick]->fd = socket;
2289 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2290 strncpy(clientlist[tempnick]->host, host,160);
2291 strncpy(clientlist[tempnick]->dhost, host,160);
2292 strncpy(clientlist[tempnick]->server, ServerName,256);
2293 strncpy(clientlist[tempnick]->ident, "unknown",9);
2294 clientlist[tempnick]->registered = 0;
2295 clientlist[tempnick]->signon = TIME+dns_timeout;
2296 clientlist[tempnick]->lastping = 1;
2297 clientlist[tempnick]->port = port;
2298 strncpy(clientlist[tempnick]->ip,ip,32);
2300 // set the registration timeout for this user
2301 unsigned long class_regtimeout = 90;
2302 int class_flood = 0;
2304 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2306 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2308 class_regtimeout = (unsigned long)i->registration_timeout;
2309 class_flood = i->flood;
2310 clientlist[tempnick]->pingmax = i->pingtime;
2315 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
2316 clientlist[tempnick]->timeout = TIME+class_regtimeout;
2317 clientlist[tempnick]->flood = class_flood;
2319 for (int i = 0; i < MAXCHANS; i++)
2321 clientlist[tempnick]->chans[i].channel = NULL;
2322 clientlist[tempnick]->chans[i].uc_modes = 0;
2325 if (clientlist.size() == MAXCLIENTS)
2326 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2329 char* e = matches_exception(ip);
2332 char* r = matches_zline(ip);
2335 char reason[MAXBUF];
2336 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2337 kill_link(clientlist[tempnick],reason);
2342 // this function counts all users connected, wether they are registered or NOT.
2345 return clientlist.size();
2348 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
2349 int registered_usercount(void)
2352 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2354 if ((i->second->fd) && (isnick(i->second->nick))) c++;
2359 int usercount_invisible(void)
2363 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2365 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2370 int usercount_opers(void)
2374 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2376 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2381 int usercount_unknown(void)
2385 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2387 if ((i->second->fd) && (i->second->registered != 7))
2393 long chancount(void)
2395 return chanlist.size();
2398 long count_servs(void)
2401 //for (int j = 0; j < 255; j++)
2403 // if (servers[j] != NULL)
2409 long servercount(void)
2411 return count_servs()+1;
2417 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2419 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2425 void ShowMOTD(userrec *user)
2427 std::string WholeMOTD = "";
2430 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2433 WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2434 for (int i = 0; i != MOTD.size(); i++)
2436 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2438 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2439 // only one write operation
2440 send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
2444 void ShowRULES(userrec *user)
2448 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2451 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2452 for (int i = 0; i != RULES.size(); i++)
2454 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2456 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2459 /* shows the message of the day, and any other on-logon stuff */
2460 void FullConnectUser(userrec* user)
2462 user->registered = 7;
2463 user->idle_lastmsg = TIME;
2464 log(DEBUG,"ConnectUser: %s",user->nick);
2466 if (strcmp(Passwd(user),"") && (!user->haspassed))
2468 kill_link(user,"Invalid password");
2473 kill_link(user,"Unauthorised connection");
2477 char match_against[MAXBUF];
2478 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2479 char* e = matches_exception(match_against);
2482 char* r = matches_gline(match_against);
2485 char reason[MAXBUF];
2486 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2487 kill_link_silent(user,reason);
2490 r = matches_kline(user->host);
2493 char reason[MAXBUF];
2494 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2495 kill_link_silent(user,reason);
2500 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2501 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2502 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2503 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2504 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2505 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2506 std::stringstream v;
2507 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2508 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2509 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2510 v << std::string(Network);
2511 std::string data005 = v.str();
2512 FOREACH_MOD On005Numeric(data005);
2513 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2514 // so i'd better split it :)
2515 std::stringstream out(data005);
2516 std::string token = "";
2517 std::string line5 = "";
2518 int token_counter = 0;
2522 line5 = line5 + token + " ";
2524 if ((token_counter >= 13) || (out.eof() == true))
2526 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2532 FOREACH_MOD OnUserConnect(user);
2533 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2535 char buffer[MAXBUF];
2536 snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2537 NetSendToAll(buffer);
2540 /* shows the message of the day, and any other on-logon stuff */
2541 void ConnectUser(userrec *user)
2543 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2544 if ((user->dns_done) && (user->registered >= 3))
2546 FullConnectUser(user);
2550 void handle_version(char **parameters, int pcnt, userrec *user)
2552 char Revision[] = "$Revision$";
2554 char *s1 = Revision;
2556 char *v1 = strtok_r(s1," ",&savept);
2558 char *v2 = strtok_r(s1," ",&savept);
2561 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2565 // calls a handler function for a command
2567 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2569 for (int i = 0; i < cmdlist.size(); i++)
2571 if (!strcasecmp(cmdlist[i].command,commandname))
2573 if (cmdlist[i].handler_function)
2575 if (pcnt>=cmdlist[i].min_params)
2577 if (strchr(user->modes,cmdlist[i].flags_needed))
2579 cmdlist[i].handler_function(parameters,pcnt,user);
2587 void DoSplitEveryone()
2589 bool go_again = true;
2593 for (int i = 0; i < 32; i++)
2597 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2599 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2602 j->CloseConnection();
2603 me[i]->connectors.erase(j);
2611 log(DEBUG,"Removed server. Will remove clients...");
2612 // iterate through the userlist and remove all users on this server.
2613 // because we're dealing with a mesh, we dont have to deal with anything
2614 // "down-route" from this server (nice huh)
2616 char reason[MAXBUF];
2620 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2622 if (strcasecmp(u->second->server,ServerName))
2624 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2625 kill_link(u->second,reason);
2635 char islast(const char* s)
2638 for (int j = 0; j < 32; j++)
2642 for (int k = 0; k < me[j]->connectors.size(); k++)
2644 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2648 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2658 long map_count(const char* s)
2661 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2663 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2669 void force_nickchange(userrec* user,const char* newnick)
2676 FOREACH_RESULT(OnUserPreNick(user,newnick));
2678 kill_link(user,"Nickname collision");
2681 if (matches_qline(newnick))
2683 kill_link(user,"Nickname collision");
2691 strncpy(nick,newnick,MAXBUF);
2693 if (user->registered == 7)
2697 handle_nick(pars,1,user);
2703 int process_parameters(char **command_p,char *parameters)
2708 q = strlen(parameters);
2711 /* no parameters, command_p invalid! */
2714 if (parameters[0] == ':')
2716 command_p[0] = parameters+1;
2721 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2723 /* only one parameter */
2724 command_p[0] = parameters;
2725 if (parameters[0] == ':')
2727 if (strchr(parameters,' ') != NULL)
2735 command_p[j++] = parameters;
2736 for (int i = 0; i <= q; i++)
2738 if (parameters[i] == ' ')
2740 command_p[j++] = parameters+i+1;
2741 parameters[i] = '\0';
2742 if (command_p[j-1][0] == ':')
2744 *command_p[j-1]++; /* remove dodgy ":" */
2746 /* parameter like this marks end of the sequence */
2750 return j; /* returns total number of items in the list */
2753 void process_command(userrec *user, char* cmd)
2757 char *command_p[127];
2758 char p[MAXBUF], temp[MAXBUF];
2759 int i, j, items, cmd_found;
2761 for (int i = 0; i < 127; i++)
2762 command_p[i] = NULL;
2772 if (!strcmp(cmd,""))
2777 int total_params = 0;
2780 for (int q = 0; q < strlen(cmd)-1; q++)
2782 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2785 // found a 'trailing', we dont count them after this.
2793 // another phidjit bug...
2794 if (total_params > 126)
2796 //kill_link(user,"Protocol violation (1)");
2797 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2801 strlcpy(temp,cmd,MAXBUF);
2803 std::string tmp = cmd;
2804 for (int i = 0; i <= MODCOUNT; i++)
2806 std::string oldtmp = tmp;
2807 modules[i]->OnServerRaw(tmp,true,user);
2810 log(DEBUG,"A Module changed the input string!");
2811 log(DEBUG,"New string: %s",tmp.c_str());
2812 log(DEBUG,"Old string: %s",oldtmp.c_str());
2816 strlcpy(cmd,tmp.c_str(),MAXBUF);
2817 strlcpy(temp,cmd,MAXBUF);
2819 if (!strchr(cmd,' '))
2821 /* no parameters, lets skip the formalities and not chop up
2823 log(DEBUG,"About to preprocess command with no params");
2825 command_p[0] = NULL;
2827 for (int i = 0; i <= strlen(cmd); i++)
2829 cmd[i] = toupper(cmd[i]);
2831 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2838 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2839 for (int i = 0; i < strlen(temp); i++)
2841 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2847 /* split the full string into a command plus parameters */
2851 if (strchr(cmd,' '))
2853 for (int i = 0; i <= strlen(cmd); i++)
2855 /* capitalise the command ONLY, leave params intact */
2856 cmd[i] = toupper(cmd[i]);
2857 /* are we nearly there yet?! :P */
2861 parameters = cmd+i+1;
2869 for (int i = 0; i <= strlen(cmd); i++)
2871 cmd[i] = toupper(cmd[i]);
2878 if (strlen(command)>MAXCOMMAND)
2880 //kill_link(user,"Protocol violation (2)");
2881 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2885 for (int x = 0; x < strlen(command); x++)
2887 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2889 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2891 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2893 //kill_link(user,"Protocol violation (3)");
2894 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2901 for (int i = 0; i != cmdlist.size(); i++)
2903 if (strcmp(cmdlist[i].command,""))
2905 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2907 log(DEBUG,"Found matching command");
2911 if (strcmp(parameters,""))
2913 items = process_parameters(command_p,parameters);
2918 command_p[0] = NULL;
2924 command_p[0] = NULL;
2929 log(DEBUG,"Processing command");
2931 /* activity resets the ping pending timer */
2932 user->nping = TIME + user->pingmax;
2933 if ((items) < cmdlist[i].min_params)
2935 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2936 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2939 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2941 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2942 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2946 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2948 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2949 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2953 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2955 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2957 if ((!isnick(user->nick)) || (user->registered != 7))
2959 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2960 WriteServ(user->fd,"451 %s :You have not registered",command);
2964 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2966 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2967 if (cmdlist[i].handler_function)
2969 /* ikky /stats counters */
2974 user->bytes_in += strlen(temp);
2976 user->bytes_out+=strlen(temp);
2979 cmdlist[i].use_count++;
2980 cmdlist[i].total_bytes+=strlen(temp);
2983 /* WARNING: nothing may come after the
2984 * command handler call, as the handler
2985 * may free the user structure! */
2987 cmdlist[i].handler_function(command_p,items,user);
2993 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2994 WriteServ(user->fd,"451 %s :You have not registered",command);
3002 if ((!cmd_found) && (user))
3004 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
3005 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3010 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
3013 /* create the command and push it onto the table */
3014 strlcpy(comm.command,cmd,MAXBUF);
3015 strlcpy(comm.source,source,MAXBUF);
3016 comm.handler_function = f;
3017 comm.flags_needed = flags;
3018 comm.min_params = minparams;
3020 comm.total_bytes = 0;
3021 cmdlist.push_back(comm);
3022 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
3025 bool removecommands(const char* source)
3027 bool go_again = true;
3031 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
3033 if (!strcmp(i->source,source))
3035 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
3045 void SetupCommandTable(void)
3047 createcommand("USER",handle_user,0,4,"<core>");
3048 createcommand("NICK",handle_nick,0,1,"<core>");
3049 createcommand("QUIT",handle_quit,0,0,"<core>");
3050 createcommand("VERSION",handle_version,0,0,"<core>");
3051 createcommand("PING",handle_ping,0,1,"<core>");
3052 createcommand("PONG",handle_pong,0,1,"<core>");
3053 createcommand("ADMIN",handle_admin,0,0,"<core>");
3054 createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
3055 createcommand("INFO",handle_info,0,0,"<core>");
3056 createcommand("TIME",handle_time,0,0,"<core>");
3057 createcommand("WHOIS",handle_whois,0,1,"<core>");
3058 createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
3059 createcommand("NOTICE",handle_notice,0,2,"<core>");
3060 createcommand("JOIN",handle_join,0,1,"<core>");
3061 createcommand("NAMES",handle_names,0,1,"<core>");
3062 createcommand("PART",handle_part,0,1,"<core>");
3063 createcommand("KICK",handle_kick,0,2,"<core>");
3064 createcommand("MODE",handle_mode,0,1,"<core>");
3065 createcommand("TOPIC",handle_topic,0,1,"<core>");
3066 createcommand("WHO",handle_who,0,1,"<core>");
3067 createcommand("MOTD",handle_motd,0,0,"<core>");
3068 createcommand("RULES",handle_rules,0,0,"<core>");
3069 createcommand("OPER",handle_oper,0,2,"<core>");
3070 createcommand("LIST",handle_list,0,0,"<core>");
3071 createcommand("DIE",handle_die,'o',1,"<core>");
3072 createcommand("RESTART",handle_restart,'o',1,"<core>");
3073 createcommand("KILL",handle_kill,'o',2,"<core>");
3074 createcommand("REHASH",handle_rehash,'o',0,"<core>");
3075 createcommand("LUSERS",handle_lusers,0,0,"<core>");
3076 createcommand("STATS",handle_stats,0,1,"<core>");
3077 createcommand("USERHOST",handle_userhost,0,1,"<core>");
3078 createcommand("AWAY",handle_away,0,0,"<core>");
3079 createcommand("ISON",handle_ison,0,0,"<core>");
3080 createcommand("SUMMON",handle_summon,0,0,"<core>");
3081 createcommand("USERS",handle_users,0,0,"<core>");
3082 createcommand("INVITE",handle_invite,0,2,"<core>");
3083 createcommand("PASS",handle_pass,0,1,"<core>");
3084 createcommand("TRACE",handle_trace,'o',0,"<core>");
3085 createcommand("WHOWAS",handle_whowas,0,1,"<core>");
3086 createcommand("CONNECT",handle_connect,'o',1,"<core>");
3087 createcommand("SQUIT",handle_squit,'o',0,"<core>");
3088 createcommand("MODULES",handle_modules,0,0,"<core>");
3089 createcommand("LINKS",handle_links,0,0,"<core>");
3090 createcommand("MAP",handle_map,0,0,"<core>");
3091 createcommand("KLINE",handle_kline,'o',1,"<core>");
3092 createcommand("GLINE",handle_gline,'o',1,"<core>");
3093 createcommand("ZLINE",handle_zline,'o',1,"<core>");
3094 createcommand("QLINE",handle_qline,'o',1,"<core>");
3095 createcommand("ELINE",handle_eline,'o',1,"<core>");
3096 createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
3097 createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
3098 createcommand("SERVER",handle_server,0,0,"<core>");
3101 void process_buffer(const char* cmdbuf,userrec *user)
3105 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3112 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3115 if (!strcmp(cmdbuf,""))
3119 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3121 strlcpy(cmd,cmdbuf,MAXBUF);
3122 if (!strcmp(cmd,""))
3126 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3128 cmd[strlen(cmd)-1] = '\0';
3130 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3132 cmd[strlen(cmd)-1] = '\0';
3135 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3137 cmd[strlen(cmd)-1] = '\0';
3140 if (!strcmp(cmd,""))
3144 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3146 if ((user) && (cmd))
3148 process_command(user,cmd);
3152 void DoSync(serverrec* serv, char* tcp_host)
3155 log(DEBUG,"Sending sync");
3156 // send start of sync marker: Y <timestamp>
3157 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3158 // except the ones its receiving it from.
3159 snprintf(data,MAXBUF,"Y %d",TIME);
3160 serv->SendPacket(data,tcp_host);
3161 // send users and channels
3162 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3164 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
3165 serv->SendPacket(data,tcp_host);
3166 if (strchr(u->second->modes,'o'))
3168 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3169 serv->SendPacket(data,tcp_host);
3171 for (int i = 0; i <= MODCOUNT; i++)
3173 string_list l = modules[i]->OnUserSync(u->second);
3174 for (int j = 0; j < l.size(); j++)
3176 strlcpy(data,l[j].c_str(),MAXBUF);
3177 serv->SendPacket(data,tcp_host);
3180 if (strcmp(chlist(u->second),""))
3182 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3183 serv->SendPacket(data,tcp_host);
3186 // send channel modes, topics etc...
3187 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3189 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3190 serv->SendPacket(data,tcp_host);
3191 for (int i = 0; i <= MODCOUNT; i++)
3193 string_list l = modules[i]->OnChannelSync(c->second);
3194 for (int j = 0; j < l.size(); j++)
3196 strlcpy(data,l[j].c_str(),MAXBUF);
3197 serv->SendPacket(data,tcp_host);
3200 if (strcmp(c->second->topic,""))
3202 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3203 serv->SendPacket(data,tcp_host);
3205 // send current banlist
3207 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3209 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3210 serv->SendPacket(data,tcp_host);
3213 // sync global zlines, glines, etc
3214 sync_xlines(serv,tcp_host);
3216 for (int j = 0; j < 32; j++)
3220 for (int k = 0; k < me[j]->connectors.size(); k++)
3222 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3224 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3225 serv->SendPacket(data,tcp_host);
3226 NetSendMyRoutingTable();
3232 snprintf(data,MAXBUF,"F %d",TIME);
3233 serv->SendPacket(data,tcp_host);
3234 log(DEBUG,"Sent sync");
3235 // ircd sends its serverlist after the end of sync here
3239 void NetSendMyRoutingTable()
3241 // send out a line saying what is reachable to us.
3242 // E.g. if A is linked to B C and D, send out:
3244 // if its only linked to B and D send out:
3246 // if it has no links, dont even send out the line at all.
3247 char buffer[MAXBUF];
3248 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3249 bool sendit = false;
3250 for (int i = 0; i < 32; i++)
3254 for (int j = 0; j < me[i]->connectors.size(); j++)
3256 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3258 strlcat(buffer," ",MAXBUF);
3259 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3266 NetSendToAll(buffer);
3270 void DoSplit(const char* params)
3272 bool go_again = true;
3276 for (int i = 0; i < 32; i++)
3280 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3282 if (!strcasecmp(j->GetServerName().c_str(),params))
3285 j->CloseConnection();
3286 me[i]->connectors.erase(j);
3294 log(DEBUG,"Removed server. Will remove clients...");
3295 // iterate through the userlist and remove all users on this server.
3296 // because we're dealing with a mesh, we dont have to deal with anything
3297 // "down-route" from this server (nice huh)
3299 char reason[MAXBUF];
3300 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3304 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3306 if (!strcasecmp(u->second->server,params))
3308 kill_link(u->second,reason);
3316 // removes a server. Will NOT remove its users!
3318 void RemoveServer(const char* name)
3320 bool go_again = true;
3324 for (int i = 0; i < 32; i++)
3328 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3330 if (!strcasecmp(j->GetServerName().c_str(),name))
3333 j->CloseConnection();
3334 me[i]->connectors.erase(j);
3345 int reap_counter = 0;
3346 char MODERR[MAXBUF];
3353 bool UnloadModule(const char* filename)
3355 for (int j = 0; j != module_names.size(); j++)
3357 if (module_names[j] == std::string(filename))
3359 if (modules[j]->GetVersion().Flags & VF_STATIC)
3361 log(DEFAULT,"Failed to unload STATIC module %s",filename);
3362 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
3366 log(DEBUG,"Deleting module...");
3369 log(DEBUG,"Deleting module factory pointer...");
3370 delete factory[j]->factory;
3371 log(DEBUG,"Deleting module factory...");
3373 log(DEBUG,"Erasing module entry...");
3375 // here we should locate ALL resources claimed by this module... and release them
3376 // for example commands
3377 log(DEBUG,"Erasing module vector...");
3378 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
3386 log(DEBUG,"Erasing module name vector...");
3387 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
3389 if (*v == std::string(filename))
3391 module_names.erase(v);
3395 log(DEBUG,"Erasing module pointer...");
3396 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
3404 log(DEBUG,"Removing dependent commands...");
3405 removecommands(filename);
3406 log(DEFAULT,"Module %s unloaded",filename);
3411 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
3412 snprintf(MODERR,MAXBUF,"Module not loaded");
3416 bool DirValid(char* dirandfile)
3419 strlcpy(work,dirandfile,MAXBUF);
3420 int p = strlen(work);
3421 // we just want the dir
3422 while (strlen(work))
3431 log(DEBUG,"Dir valid: %s",work);
3432 char buffer[MAXBUF], otherdir[MAXBUF];
3433 // Get the current working directory
3434 if( getcwd( buffer, MAXBUF ) == NULL )
3437 if( getcwd( otherdir, MAXBUF ) == NULL )
3440 log(DEBUG,"Dir is really: %s",otherdir);
3441 if (strlen(otherdir) >= strlen(work))
3443 otherdir[strlen(work)] = '\0';
3444 log(DEBUG,"Compare: '%s' -> '%s'",otherdir,work);
3445 if (!strcmp(otherdir,work))
3447 log(DEBUG,"Match ok");
3450 log(DEBUG,"No match");
3456 bool LoadModule(const char* filename)
3458 char modfile[MAXBUF];
3459 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
3460 if (!DirValid(modfile))
3462 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
3463 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
3466 log(DEBUG,"Loading module: %s",modfile);
3467 if (FileExists(modfile))
3469 for (int j = 0; j < module_names.size(); j++)
3471 if (module_names[j] == std::string(filename))
3473 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
3474 snprintf(MODERR,MAXBUF,"Module already loaded");
3478 factory[MODCOUNT+1] = new ircd_module(modfile);
3479 if (factory[MODCOUNT+1]->LastError())
3481 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
3482 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
3486 if (factory[MODCOUNT+1]->factory)
3488 modules[MODCOUNT+1] = factory[MODCOUNT+1]->factory->CreateModule();
3489 /* save the module and the module's classfactory, if
3490 * this isnt done, random crashes can occur :/ */
3491 module_names.push_back(filename);
3495 log(DEFAULT,"Unable to load %s",modfile);
3496 snprintf(MODERR,MAXBUF,"Factory function failed!");
3502 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
3503 snprintf(MODERR,MAXBUF,"Module file could not be found");
3512 struct sockaddr_in client,server;
3513 char addrs[MAXBUF][255];
3514 int incomingSockfd, result = TRUE;
3517 int selectResult = 0, selectResult2 = 0;
3518 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3519 char resolvedHost[MAXBUF];
3523 log_file = fopen("ircd.log","a+");
3526 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3530 log(DEBUG,"InspIRCd: startup: begin");
3534 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3536 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
3538 SetupCommandTable();
3539 log(DEBUG,"InspIRCd: startup: default command table set up");
3541 ReadConfig(true,NULL);
3542 if (strcmp(DieValue,""))
3544 printf("WARNING: %s\n\n",DieValue);
3545 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3548 log(DEBUG,"InspIRCd: startup: read config");
3550 int count2 = 0, count3 = 0;
3552 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3554 ConfValue("bind","port",count,configToken,&config_f);
3555 ConfValue("bind","address",count,Addr,&config_f);
3556 ConfValue("bind","type",count,Type,&config_f);
3557 if (!strcmp(Type,"servers"))
3559 char Default[MAXBUF];
3560 strcpy(Default,"no");
3561 ConfValue("bind","default",count,Default,&config_f);
3562 if (strchr(Default,'y'))
3564 defaultRoute = count3;
3565 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3567 me[count3] = new serverrec(ServerName,100L,false);
3568 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3570 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3579 ports[count2] = atoi(configToken);
3580 strlcpy(addrs[count2],Addr,256);
3583 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3586 UDPportCount = count3;
3588 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3590 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3594 /* BugFix By Craig! :p */
3596 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3598 ConfValue("module","name",count2,configToken,&config_f);
3599 printf("Loading module... \033[1;37m%s\033[0;37m\n",configToken);
3600 if (!LoadModule(configToken))
3602 log(DEBUG,"Exiting due to a module loader error.");
3603 printf("There was an error loading a module: %s\n",ModuleError());
3607 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3609 printf("\nInspIRCd is now running!\n");
3611 startup_time = time(NULL);
3615 log(VERBOSE,"Not forking as -nofork was specified");
3619 if (DaemonSeed() == ERROR)
3621 log(DEFAULT,"InspIRCd: startup: can't daemonise");
3622 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3628 ConfValue("pid","file",0,PID,&config_f);
3632 /* setup select call */
3633 FD_ZERO(&selectFds);
3634 log(DEBUG,"InspIRCd: startup: zero selects");
3635 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3637 for (count = 0; count < portCount; count++)
3639 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3641 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3644 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3646 log(DEFAULT,"InspIRCd: startup: failed to bind port %d",ports[count]);
3648 else /* well we at least bound to one socket so we'll continue */
3654 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3656 /* if we didn't bind to anything then abort */
3657 if (boundPortCount == 0)
3659 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
3664 length = sizeof (client);
3665 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3669 tvs.tv_usec = 7000L;
3676 tval.tv_usec = 7000L;
3678 int total_in_this_set = 0;
3680 bool expire_run = false;
3682 /* main loop, this never returns */
3685 #ifdef _POSIX_PRIORITY_SCHEDULING
3692 // we only read time() once per iteration rather than tons of times!
3695 user_hash::iterator count2 = clientlist.begin();
3697 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3698 // them in a list, then reap the list every second or so.
3699 if (((TIME % 5) == 0) && (!expire_run))
3704 if ((TIME % 5) == 1)
3706 if (reap_counter>300)
3708 if (fd_reap.size() > 0)
3710 for( int n = 0; n < fd_reap.size(); n++)
3712 //Blocking(fd_reap[n]);
3714 shutdown (fd_reap[n],2);
3715 //NonBlocking(fd_reap[n]);
3723 FD_ZERO(&serverfds);
3725 for (int x = 0; x != UDPportCount; x++)
3728 FD_SET(me[x]->fd, &serverfds);
3731 // serverFds timevals went here
3733 tvs.tv_usec = 7000L;
3734 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3737 for (int x = 0; x != UDPportCount; x++)
3739 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3741 char remotehost[MAXBUF],resolved[MAXBUF];
3742 length = sizeof (client);
3743 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3744 if (incomingSockfd != -1)
3746 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3747 if(CleanAndResolve(resolved, remotehost) != TRUE)
3749 strlcpy(resolved,remotehost,MAXBUF);
3751 // add to this connections ircd_connector vector
3752 // *FIX* - we need the LOCAL port not the remote port in &client!
3753 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3759 for (int x = 0; x < UDPportCount; x++)
3761 std::deque<std::string> msgs;
3763 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3765 for (int ctr = 0; ctr < msgs.size(); ctr++)
3767 char udp_msg[MAXBUF];
3768 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3769 if (strlen(udp_msg)<1)
3771 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3774 // during a netburst, send all data to all other linked servers
3775 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3777 if (is_uline(tcp_host))
3779 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3781 NetSendToAllExcept(tcp_host,udp_msg);
3785 NetSendToAllExcept(tcp_host,udp_msg);
3787 FOREACH_MOD OnPacketReceive(udp_msg);
3788 handle_link_packet(udp_msg, tcp_host, me[x]);
3795 while (count2 != clientlist.end())
3798 total_in_this_set = 0;
3800 user_hash::iterator xcount = count2;
3801 user_hash::iterator endingiter = count2;
3803 if (count2 == clientlist.end()) break;
3806 if (count2->second->fd != 0)
3808 // assemble up to 64 sockets into an fd_set
3809 // to implement a pooling mechanism.
3811 // This should be up to 64x faster than the
3812 // old implementation.
3813 while (total_in_this_set < 64)
3815 if (count2 != clientlist.end())
3817 // we don't check the state of remote users.
3818 if (count2->second->fd > 0)
3820 FD_SET (count2->second->fd, &sfd);
3822 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3823 // their connection class.
3824 if ((TIME > count2->second->timeout) && (count2->second->registered != 7))
3826 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3827 kill_link(count2->second,"Registration timeout");
3830 if ((TIME > count2->second->signon) && (count2->second->registered == 3))
3832 count2->second->dns_done = true;
3833 FullConnectUser(count2->second);
3836 if ((count2->second->dns_done) && (count2->second->registered == 3)) // both NICK and USER... and DNS
3838 FullConnectUser(count2->second);
3841 if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3843 if ((!count2->second->lastping) && (count2->second->registered == 7))
3845 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3846 kill_link(count2->second,"Ping timeout");
3849 Write(count2->second->fd,"PING :%s",ServerName);
3850 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3851 count2->second->lastping = 0;
3852 count2->second->nping = TIME+count2->second->pingmax; // was hard coded to 120
3856 total_in_this_set++;
3861 endingiter = count2;
3862 count2 = xcount; // roll back to where we were
3866 // tvals defined here
3868 tval.tv_usec = 7000L;
3869 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3871 // now loop through all of the items in this pool if any are waiting
3872 //if (selectResult2 > 0)
3873 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3876 #ifdef _POSIX_PRIORITY_SCHEDULING
3881 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3883 memset(data, 0, 10240);
3884 result = read(count2a->second->fd, data, 10240);
3888 userrec* current = count2a->second;
3889 int currfd = current->fd;
3890 char* l = strtok(data,"\n");
3895 if ((floodlines > current->flood) && (current->flood != 0))
3897 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3898 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3899 kill_link(current,"Excess flood");
3902 char sanitized[NetBufferSize];
3903 memset(sanitized, 0, NetBufferSize);
3905 for (int pt = 0; pt < strlen(l); pt++)
3909 sanitized[ptt++] = l[pt];
3912 sanitized[ptt] = '\0';
3913 if (strlen(sanitized))
3917 // we're gonna re-scan to check if the nick is gone, after every
3918 // command - if it has, we're gonna bail
3919 bool find_again = false;
3920 process_buffer(sanitized,current);
3922 // look for the user's record in case it's changed
3923 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3925 if (c2->second->fd == currfd)
3927 // found again, update pointer
3928 current == c2->second;
3937 l = strtok(NULL,"\n");
3942 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3944 log(DEBUG,"killing: %s",count2a->second->nick);
3945 kill_link(count2a->second,strerror(errno));
3949 // result EAGAIN means nothing read
3950 if (result == EAGAIN)
3958 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3959 kill_link(count2a->second,"Client exited");
3960 // must bail here? kill_link removes the hash, corrupting the iterator
3961 log(DEBUG,"Bailing from client exit");
3965 else if (result > 0)
3970 for (int q = 0; q < total_in_this_set; q++)
3972 // there is no iterator += operator :(
3973 //if (count2 != clientlist.end())
3980 // set up select call
3981 for (count = 0; count < boundPortCount; count++)
3983 FD_SET (openSockfd[count], &selectFds);
3987 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3989 /* select is reporting a waiting socket. Poll them all to find out which */
3990 if (selectResult > 0)
3992 char target[MAXBUF], resolved[MAXBUF];
3993 for (count = 0; count < boundPortCount; count++)
3995 if (FD_ISSET (openSockfd[count], &selectFds))
3997 length = sizeof (client);
3998 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4000 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4001 strlcpy (resolved, target, MAXBUF);
4003 if (incomingSockfd < 0)
4005 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4006 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4010 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
4011 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4018 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
4021 close (incomingSockfd);