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;
197 long MyKey = C.GenKey();
201 int has_channel(userrec *u, chanrec *c);
202 int usercount(chanrec *c);
203 int usercount_i(chanrec *c);
204 char* Passwd(userrec *user);
205 bool IsDenied(userrec *user);
206 void AddWhoWas(userrec* u);
208 std::vector<long> auth_cookies;
209 std::stringstream config_f(stringstream::in | stringstream::out);
215 char Revision[] = "$Revision$";
218 char *v1 = strtok_r(s1," ",&savept);
220 char *v2 = strtok_r(s1," ",&savept);
222 return (long)(atof(v2)*10000);
226 std::string getservername()
231 std::string getserverdesc()
236 std::string getnetworkname()
241 std::string getadminname()
246 std::string getadminemail()
251 std::string getadminnick()
256 void log(int level,char *text, ...)
258 char textbuffer[MAXBUF];
261 struct tm * timeinfo;
262 if (level < LogLevel)
266 timeinfo = localtime (&rawtime);
271 va_start (argsPtr, text);
272 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
274 strlcpy(b,asctime(timeinfo),MAXBUF);
275 b[strlen(b)-1] = ':';
276 fprintf(log_file,"%s %s\n",b,textbuffer);
279 // nofork enabled? display it on terminal too
280 printf("%s %s\n",b,textbuffer);
285 void readfile(file_cache &F, const char* fname)
288 char linebuf[MAXBUF];
290 log(DEBUG,"readfile: loading %s",fname);
292 file = fopen(fname,"r");
297 fgets(linebuf,sizeof(linebuf),file);
298 linebuf[strlen(linebuf)-1]='\0';
299 if (!strcmp(linebuf,""))
305 F.push_back(linebuf);
312 log(DEBUG,"readfile: failed to load file: %s",fname);
314 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
317 void ReadConfig(bool bail, userrec* user)
319 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
320 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF];
322 std::stringstream errstr;
324 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
329 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
337 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
338 while (!errstr.eof())
340 errstr.getline(dataline,1024);
341 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
346 WriteOpers("There were errors in the configuration file:",user->nick);
347 while (!errstr.eof())
349 errstr.getline(dataline,1024);
350 WriteOpers(dataline);
357 ConfValue("server","name",0,ServerName,&config_f);
358 ConfValue("server","description",0,ServerDesc,&config_f);
359 ConfValue("server","network",0,Network,&config_f);
360 ConfValue("admin","name",0,AdminName,&config_f);
361 ConfValue("admin","email",0,AdminEmail,&config_f);
362 ConfValue("admin","nick",0,AdminNick,&config_f);
363 ConfValue("files","motd",0,motd,&config_f);
364 ConfValue("files","rules",0,rules,&config_f);
365 ConfValue("power","diepass",0,diepass,&config_f);
366 ConfValue("power","pause",0,pauseval,&config_f);
367 ConfValue("power","restartpass",0,restartpass,&config_f);
368 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
369 ConfValue("die","value",0,DieValue,&config_f);
370 ConfValue("options","loglevel",0,dbg,&config_f);
371 ConfValue("options","netbuffersize",0,NB,&config_f);
372 ConfValue("options","maxwho",0,MW,&config_f);
373 ConfValue("options","allowhalfop",0,AH,&config_f);
374 ConfValue("options","allowprotect",0,AP,&config_f);
375 ConfValue("options","allowfounder",0,AF,&config_f);
376 ConfValue("dns","server",0,DNSServer,&config_f);
377 ConfValue("dns","timeout",0,DNT,&config_f);
378 NetBufferSize = atoi(NB);
379 MaxWhoResults = atoi(MW);
380 dns_timeout = atoi(DNT);
383 if (!strcmp(DNSServer,""))
384 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
385 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
386 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
387 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
388 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
390 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
391 NetBufferSize = 10240;
393 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
395 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
398 if (!strcmp(dbg,"debug"))
400 if (!strcmp(dbg,"verbose"))
402 if (!strcmp(dbg,"default"))
404 if (!strcmp(dbg,"sparse"))
406 if (!strcmp(dbg,"none"))
409 log(DEFAULT,"Reading message of the day...");
410 readfile(RULES,rules);
411 log(DEFAULT,"Reading connect classes...");
413 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
416 ConfValue("connect","allow",i,Value,&config_f);
417 ConfValue("connect","timeout",i,timeout,&config_f);
418 ConfValue("connect","flood",i,flood,&config_f);
419 if (strcmp(Value,""))
421 strlcpy(c.host,Value,MAXBUF);
423 strlcpy(Value,"",MAXBUF);
424 ConfValue("connect","password",i,Value,&config_f);
425 strlcpy(c.pass,Value,MAXBUF);
426 c.registration_timeout = 90; // default is 2 minutes
427 c.flood = atoi(flood);
430 c.registration_timeout = atoi(timeout);
432 Classes.push_back(c);
433 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
437 ConfValue("connect","deny",i,Value,&config_f);
438 strlcpy(c.host,Value,MAXBUF);
440 Classes.push_back(c);
441 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
445 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
446 read_xline_defaults();
447 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
449 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
452 log(DEFAULT,"Adding and removing modules due to rehash...");
454 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
456 // store the old module names
457 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
459 old_module_names.push_back(*t);
462 // get the new module names
463 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
465 ConfValue("module","name",count2,Value,&config_f);
466 new_module_names.push_back(Value);
469 // now create a list of new modules that are due to be loaded
470 // and a seperate list of modules which are due to be unloaded
471 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
474 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
480 added_modules.push_back(*_new);
482 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
485 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
491 removed_modules.push_back(*oldm);
493 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
495 int rem = 0, add = 0;
496 if (!removed_modules.empty())
497 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
499 if (UnloadModule(removing->c_str()))
501 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
502 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
507 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
510 if (!added_modules.empty())
511 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
513 if (LoadModule(adding->c_str()))
515 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
516 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
521 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
524 log(DEFAULT,"Successfully unloaded %d of %d modules and loaded %d of %d modules.",rem,removed_modules.size(),add,added_modules.size());
528 /* write formatted text to a socket, in same format as printf */
530 void Write(int sock,char *text, ...)
534 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
537 char textbuffer[MAXBUF];
541 va_start (argsPtr, text);
542 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
544 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
548 write(sock,tb,strlen(tb));
552 /* write a server formatted numeric response to a single socket */
554 void WriteServ(int sock, char* text, ...)
558 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
561 char textbuffer[MAXBUF],tb[MAXBUF];
563 va_start (argsPtr, text);
565 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
567 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
571 write(sock,tb,strlen(tb));
575 /* write text from an originating user to originating user */
577 void WriteFrom(int sock, userrec *user,char* text, ...)
579 if ((!text) || (!user))
581 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
584 char textbuffer[MAXBUF],tb[MAXBUF];
586 va_start (argsPtr, text);
588 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
590 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
594 write(sock,tb,strlen(tb));
598 /* write text to an destination user from a source user (e.g. user privmsg) */
600 void WriteTo(userrec *source, userrec *dest,char *data, ...)
602 if ((!dest) || (!data))
604 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
607 char textbuffer[MAXBUF],tb[MAXBUF];
609 va_start (argsPtr, data);
610 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
614 // if no source given send it from the server.
617 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
621 WriteFrom(dest->fd,source,"%s",textbuffer);
625 /* write formatted text from a source user to all users on a channel
626 * including the sender (NOT for privmsg, notice etc!) */
628 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
630 if ((!Ptr) || (!user) || (!text))
632 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
635 char textbuffer[MAXBUF];
637 va_start (argsPtr, text);
638 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
640 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
642 if (has_channel(i->second,Ptr))
644 WriteTo(user,i->second,"%s",textbuffer);
649 /* write formatted text from a source user to all users on a channel
650 * including the sender (NOT for privmsg, notice etc!) doesnt send to
651 * users on remote servers */
653 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
655 if ((!Ptr) || (!text))
657 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
660 char textbuffer[MAXBUF];
662 va_start (argsPtr, text);
663 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
665 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
667 if (has_channel(i->second,Ptr))
669 if (i->second->fd != -1)
673 WriteServ(i->second->fd,"%s",textbuffer);
677 WriteTo(user,i->second,"%s",textbuffer);
685 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
687 if ((!Ptr) || (!user) || (!text))
689 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
692 char textbuffer[MAXBUF];
694 va_start (argsPtr, text);
695 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
697 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
701 if (has_channel(i->second,Ptr))
703 WriteServ(i->second->fd,"%s",textbuffer);
710 /* write formatted text from a source user to all users on a channel except
711 * for the sender (for privmsg etc) */
713 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
715 if ((!Ptr) || (!user) || (!text))
717 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
720 char textbuffer[MAXBUF];
722 va_start (argsPtr, text);
723 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
726 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
730 if (has_channel(i->second,Ptr) && (user != i->second))
732 WriteTo(user,i->second,"%s",textbuffer);
739 std::string GetServerDescription(char* servername)
741 for (int j = 0; j < 32; j++)
745 for (int k = 0; k < me[j]->connectors.size(); k++)
747 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
749 return me[j]->connectors[k].GetDescription();
753 return ServerDesc; // not a remote server that can be found, it must be me.
758 /* write a formatted string to all users who share at least one common
759 * channel, including the source user e.g. for use in NICK */
761 void WriteCommon(userrec *u, char* text, ...)
765 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
769 if (u->registered != 7) {
770 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
774 char textbuffer[MAXBUF];
776 va_start (argsPtr, text);
777 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
780 WriteFrom(u->fd,u,"%s",textbuffer);
782 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
786 if (common_channels(u,i->second) && (i->second != u))
788 WriteFrom(i->second->fd,u,"%s",textbuffer);
794 /* write a formatted string to all users who share at least one common
795 * channel, NOT including the source user e.g. for use in QUIT */
797 void WriteCommonExcept(userrec *u, char* text, ...)
801 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
805 if (u->registered != 7) {
806 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
810 char textbuffer[MAXBUF];
812 va_start (argsPtr, text);
813 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
816 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
820 if ((common_channels(u,i->second)) && (u != i->second))
822 WriteFrom(i->second->fd,u,"%s",textbuffer);
828 void WriteOpers(char* text, ...)
832 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
836 char textbuffer[MAXBUF];
838 va_start (argsPtr, text);
839 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
842 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
846 if (strchr(i->second->modes,'o'))
848 if (strchr(i->second->modes,'s'))
850 // send server notices to all with +s
851 // (TODO: needs SNOMASKs)
852 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
859 // returns TRUE of any users on channel C occupy server 'servername'.
861 bool ChanAnyOnThisServer(chanrec *c,char* servername)
863 log(DEBUG,"ChanAnyOnThisServer");
864 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
866 if (has_channel(i->second,c))
868 if (!strcasecmp(i->second->server,servername))
877 // returns true if user 'u' shares any common channels with any users on server 'servername'
879 bool CommonOnThisServer(userrec* u,const char* servername)
881 log(DEBUG,"ChanAnyOnThisServer");
882 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
884 if ((common_channels(u,i->second)) && (u != i->second))
886 if (!strcasecmp(i->second->server,servername))
888 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
897 void NetSendToCommon(userrec* u, char* s)
900 snprintf(buffer,MAXBUF,"%s",s);
902 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
904 for (int j = 0; j < 32; j++)
908 for (int k = 0; k < me[j]->connectors.size(); k++)
910 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
912 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
920 void NetSendToAll(char* s)
923 snprintf(buffer,MAXBUF,"%s",s);
925 log(DEBUG,"NetSendToAll: '%s'",s);
927 for (int j = 0; j < 32; j++)
931 for (int k = 0; k < me[j]->connectors.size(); k++)
933 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
939 void NetSendToAllAlive(char* s)
942 snprintf(buffer,MAXBUF,"%s",s);
944 log(DEBUG,"NetSendToAllAlive: '%s'",s);
946 for (int j = 0; j < 32; j++)
950 for (int k = 0; k < me[j]->connectors.size(); k++)
952 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
954 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
958 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
966 void NetSendToOne(char* target,char* s)
969 snprintf(buffer,MAXBUF,"%s",s);
971 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
973 for (int j = 0; j < 32; j++)
977 for (int k = 0; k < me[j]->connectors.size(); k++)
979 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
981 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
988 void NetSendToAllExcept(const char* target,char* s)
991 snprintf(buffer,MAXBUF,"%s",s);
993 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
995 for (int j = 0; j < 32; j++)
999 for (int k = 0; k < me[j]->connectors.size(); k++)
1001 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1003 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1011 void WriteMode(const char* modes, int flags, const char* text, ...)
1013 if ((!text) || (!modes) || (!flags))
1015 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1019 char textbuffer[MAXBUF];
1021 va_start (argsPtr, text);
1022 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1025 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1029 bool send_to_user = false;
1031 if (flags == WM_AND)
1033 send_to_user = true;
1034 for (int n = 0; n < strlen(modes); n++)
1036 if (!hasumode(i->second,modes[n]))
1038 send_to_user = false;
1043 else if (flags == WM_OR)
1045 send_to_user = false;
1046 for (int n = 0; n < strlen(modes); n++)
1048 if (hasumode(i->second,modes[n]))
1050 send_to_user = true;
1058 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1065 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1067 if ((!text) || (!source))
1069 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1074 char textbuffer[MAXBUF];
1076 va_start (argsPtr, text);
1077 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1080 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1084 if (strchr(i->second->modes,'w'))
1086 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1093 char buffer[MAXBUF];
1094 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1095 NetSendToAll(buffer);
1099 /* convert a string to lowercase. Note following special circumstances
1100 * taken from RFC 1459. Many "official" server branches still hold to this
1101 * rule so i will too;
1103 * Because of IRC's scandanavian origin, the characters {}| are
1104 * considered to be the lower case equivalents of the characters []\,
1105 * respectively. This is a critical issue when determining the
1106 * equivalence of two nicknames.
1109 void strlower(char *n)
1115 for (int i = 0; i != strlen(n); i++)
1117 n[i] = tolower(n[i]);
1129 /* Find a user record by nickname and return a pointer to it */
1131 userrec* Find(std::string nick)
1133 user_hash::iterator iter = clientlist.find(nick);
1135 if (iter == clientlist.end())
1136 /* Couldn't find it */
1139 return iter->second;
1142 /* find a channel record by channel name and return a pointer to it */
1144 chanrec* FindChan(const char* chan)
1148 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1152 chan_hash::iterator iter = chanlist.find(chan);
1154 if (iter == chanlist.end())
1155 /* Couldn't find it */
1158 return iter->second;
1162 long GetMaxBans(char* name)
1165 for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1167 ConfValue("banlist","chan",count,CM,&config_f);
1170 ConfValue("banlist","limit",count,CM,&config_f);
1178 void purge_empty_chans(void)
1180 int go_again = 1, purge = 0;
1185 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1188 if (!usercount(i->second))
1190 /* kill the record */
1191 if (i != chanlist.end())
1193 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1194 if (i->second) delete i->second;
1203 log(DEBUG,"skipped purge for %s",i->second->name);
1208 log(DEBUG,"completed channel purge, killed %d",purge);
1212 char scratch[MAXBUF];
1213 char sparam[MAXBUF];
1215 char* chanmodes(chanrec *chan)
1219 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1226 if (chan->noexternal)
1228 strlcat(scratch,"n",MAXMODES);
1230 if (chan->topiclock)
1232 strlcat(scratch,"t",MAXMODES);
1234 if (strcmp(chan->key,""))
1236 strlcat(scratch,"k",MAXMODES);
1240 strlcat(scratch,"l",MAXMODES);
1242 if (chan->inviteonly)
1244 strlcat(scratch,"i",MAXMODES);
1246 if (chan->moderated)
1248 strlcat(scratch,"m",MAXMODES);
1252 strlcat(scratch,"s",MAXMODES);
1254 if (chan->c_private)
1256 strlcat(scratch,"p",MAXMODES);
1258 if (strcmp(chan->key,""))
1260 strlcat(sparam," ",MAXBUF);
1261 strlcat(sparam,chan->key,MAXBUF);
1266 sprintf(foo," %d",chan->limit);
1267 strlcat(sparam,foo,MAXBUF);
1269 if (strlen(chan->custom_modes))
1271 strlcat(scratch,chan->custom_modes,MAXMODES);
1272 for (int z = 0; z < strlen(chan->custom_modes); z++)
1274 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1277 strlcat(sparam," ",MAXBUF);
1278 strlcat(sparam,extparam.c_str(),MAXBUF);
1282 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1283 strlcat(scratch,sparam,MAXMODES);
1288 /* compile a userlist of a channel into a string, each nick seperated by
1289 * spaces and op, voice etc status shown as @ and + */
1291 void userlist(userrec *user,chanrec *c)
1293 if ((!c) || (!user))
1295 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1299 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1300 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1302 if (has_channel(i->second,c))
1304 if (isnick(i->second->nick))
1306 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1308 /* user is +i, and source not on the channel, does not show
1309 * nick in NAMES list */
1312 strlcat(list,cmode(i->second,c),MAXBUF);
1313 strlcat(list,i->second->nick,MAXBUF);
1314 strlcat(list," ",MAXBUF);
1315 if (strlen(list)>(480-NICKMAX))
1317 /* list overflowed into
1318 * multiple numerics */
1319 WriteServ(user->fd,"%s",list);
1320 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1325 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1327 WriteServ(user->fd,"%s",list);
1331 /* return a count of the users on a specific channel accounting for
1332 * invisible users who won't increase the count. e.g. for /LIST */
1334 int usercount_i(chanrec *c)
1341 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1346 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1350 if (has_channel(i->second,c))
1352 if (isnick(i->second->nick))
1354 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1356 /* user is +i, and source not on the channel, does not show
1357 * nick in NAMES list */
1365 log(DEBUG,"usercount_i: %s %d",c->name,count);
1370 int usercount(chanrec *c)
1377 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1382 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1386 if (has_channel(i->second,c))
1388 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1395 log(DEBUG,"usercount: %s %d",c->name,count);
1400 /* add a channel to a user, creating the record for it if needed and linking
1401 * it to the user record */
1403 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1405 if ((!user) || (!cn))
1407 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1416 strncpy(cname,cn,MAXBUF);
1418 // we MUST declare this wherever we use FOREACH_RESULT
1421 if (strlen(cname) > CHANMAX-1)
1423 cname[CHANMAX-1] = '\0';
1426 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1428 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1430 return NULL; // already on the channel!
1434 if (!FindChan(cname))
1437 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1438 if (MOD_RESULT == 1) {
1442 /* create a new one */
1443 log(DEBUG,"add_channel: creating: %s",cname);
1445 chanlist[cname] = new chanrec();
1447 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1448 chanlist[cname]->topiclock = 1;
1449 chanlist[cname]->noexternal = 1;
1450 chanlist[cname]->created = TIME;
1451 strcpy(chanlist[cname]->topic, "");
1452 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1453 chanlist[cname]->topicset = 0;
1454 Ptr = chanlist[cname];
1455 log(DEBUG,"add_channel: created: %s",cname);
1456 /* set created to 2 to indicate user
1457 * is the first in the channel
1458 * and should be given ops */
1464 /* channel exists, just fish out a pointer to its struct */
1465 Ptr = FindChan(cname);
1468 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1470 // the override flag allows us to bypass channel modes
1471 // and bans (used by servers)
1472 if ((!override) || (!strcasecmp(user->server,ServerName)))
1474 log(DEBUG,"Not overriding...");
1476 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1477 if (MOD_RESULT == 1) {
1480 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1484 log(DEBUG,"add_channel: checking key, invite, etc");
1485 if (strcmp(Ptr->key,""))
1487 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1490 log(DEBUG,"add_channel: no key given in JOIN");
1491 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1496 log(DEBUG,"key at %p is %s",key,key);
1497 if (strcasecmp(key,Ptr->key))
1499 log(DEBUG,"add_channel: bad key given in JOIN");
1500 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1505 log(DEBUG,"add_channel: no key");
1507 if (Ptr->inviteonly)
1509 log(DEBUG,"add_channel: channel is +i");
1510 if (user->IsInvited(Ptr->name))
1512 /* user was invited to channel */
1513 /* there may be an optional channel NOTICE here */
1517 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1521 log(DEBUG,"add_channel: channel is not +i");
1525 if (usercount(Ptr) == Ptr->limit)
1527 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1532 log(DEBUG,"add_channel: about to walk banlist");
1534 /* check user against the channel banlist */
1537 if (Ptr->bans.size())
1539 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1541 if (match(user->GetFullHost(),i->data))
1543 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1550 log(DEBUG,"add_channel: bans checked");
1555 if ((Ptr) && (user))
1557 user->RemoveInvite(Ptr->name);
1560 log(DEBUG,"add_channel: invites removed");
1565 log(DEBUG,"Overridden checks");
1573 log(DEBUG,"Passed channel checks");
1575 for (int i =0; i != MAXCHANS; i++)
1577 log(DEBUG,"Check location %d",i);
1578 if (user->chans[i].channel == NULL)
1580 log(DEBUG,"Adding into their channel list at location %d",i);
1584 /* first user in is given ops */
1585 user->chans[i].uc_modes = UCMODE_OP;
1589 user->chans[i].uc_modes = 0;
1591 user->chans[i].channel = Ptr;
1592 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1594 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1596 // use the stamdard J token with no privilages.
1597 char buffer[MAXBUF];
1600 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1604 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1606 NetSendToAll(buffer);
1609 log(DEBUG,"Sent JOIN to client");
1613 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1614 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1617 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1618 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1619 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1620 FOREACH_MOD OnUserJoin(user,Ptr);
1624 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1625 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1629 /* remove a channel from a users record, and remove the record from memory
1630 * if the channel has become empty */
1632 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1634 if ((!user) || (!cname))
1636 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1643 if ((!cname) || (!user))
1648 Ptr = FindChan(cname);
1655 FOREACH_MOD OnUserPart(user,Ptr);
1656 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1658 for (int i =0; i != MAXCHANS; i++)
1660 /* zap it from the channel list of the user */
1661 if (user->chans[i].channel == Ptr)
1665 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1669 char buffer[MAXBUF];
1670 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1671 NetSendToAll(buffer);
1680 char buffer[MAXBUF];
1681 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1682 NetSendToAll(buffer);
1685 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1687 user->chans[i].uc_modes = 0;
1688 user->chans[i].channel = NULL;
1689 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1694 /* if there are no users left on the channel */
1695 if (!usercount(Ptr))
1697 chan_hash::iterator iter = chanlist.find(Ptr->name);
1699 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1701 /* kill the record */
1702 if (iter != chanlist.end())
1704 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1705 if (iter->second) delete iter->second;
1706 chanlist.erase(iter);
1712 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1714 if ((!src) || (!user) || (!Ptr) || (!reason))
1716 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1723 if ((!Ptr) || (!user) || (!src))
1728 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1730 if (!has_channel(user,Ptr))
1732 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1737 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1739 if (MOD_RESULT == ACR_DENY)
1742 if (MOD_RESULT == ACR_DEFAULT)
1744 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1746 if (cstatus(src,Ptr) == STATUS_HOP)
1748 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1752 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1759 for (int i =0; i != MAXCHANS; i++)
1761 /* zap it from the channel list of the user */
1762 if (user->chans[i].channel)
1763 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1765 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1766 user->chans[i].uc_modes = 0;
1767 user->chans[i].channel = NULL;
1768 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1773 /* if there are no users left on the channel */
1774 if (!usercount(Ptr))
1776 chan_hash::iterator iter = chanlist.find(Ptr->name);
1778 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1780 /* kill the record */
1781 if (iter != chanlist.end())
1783 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1784 if (iter->second) delete iter->second;
1785 chanlist.erase(iter);
1793 /* This function pokes and hacks at a parameter list like the following:
1795 * PART #winbot,#darkgalaxy :m00!
1797 * to turn it into a series of individual calls like this:
1799 * PART #winbot :m00!
1800 * PART #darkgalaxy :m00!
1802 * The seperate calls are sent to a callback function provided by the caller
1803 * (the caller will usually call itself recursively). The callback function
1804 * must be a command handler. Calling this function on a line with no list causes
1805 * no action to be taken. You must provide a starting and ending parameter number
1806 * where the range of the list can be found, useful if you have a terminating
1807 * parameter as above which is actually not part of the list, or parameters
1808 * before the actual list as well. This code is used by many functions which
1809 * can function as "one to list" (see the RFC) */
1811 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1816 char blog[32][MAXBUF];
1817 char blog2[32][MAXBUF];
1818 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1819 char keystr[MAXBUF];
1822 for (int i = 0; i <32; i++)
1825 for (int i = 0; i <32; i++)
1826 strcpy(blog2[i],"");
1829 for (int i = 0; i <10; i++)
1833 parameters[i] = moo;
1838 if (pcnt > 1) /* we have a key to copy */
1840 strlcpy(keystr,parameters[1],MAXBUF);
1844 if (!parameters[start])
1848 if (!strchr(parameters[start],','))
1853 for (int i = start; i <= end; i++)
1857 strlcat(plist,parameters[i],MAXBUF);
1865 for (int i = 0; i < t; i++)
1867 if (plist[i] == ',')
1870 strlcpy(blog[j++],param,MAXBUF);
1874 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1879 strlcpy(blog[j++],param,MAXBUF);
1882 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1887 if ((joins) && (keystr))
1889 if (strchr(keystr,','))
1893 t2 = strlen(keystr);
1894 for (int i = 0; i < t2; i++)
1896 if (keystr[i] == ',')
1899 strlcpy(blog2[j++],param,MAXBUF);
1903 strlcpy(blog2[j++],param,MAXBUF);
1908 for (j = 0; j < total; j++)
1914 for (q = end; q < pcnt-1; q++)
1916 if (parameters[q+1])
1918 pars[q-end+1] = parameters[q+1];
1921 if ((joins) && (parameters[1]))
1932 /* repeatedly call the function with the hacked parameter list */
1933 if ((joins) && (pcnt > 1))
1937 // pars[1] already set up and containing key from blog2[j]
1942 pars[1] = parameters[1];
1948 fn(pars,pcnt-(end-start),u);
1957 void kill_link(userrec *user,const char* r)
1959 user_hash::iterator iter = clientlist.find(user->nick);
1961 char reason[MAXBUF];
1963 strncpy(reason,r,MAXBUF);
1965 if (strlen(reason)>MAXQUIT)
1967 reason[MAXQUIT-1] = '\0';
1970 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1971 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1972 log(DEBUG,"closing fd %d",user->fd);
1974 /* bugfix, cant close() a nonblocking socket (sux!) */
1975 if (user->registered == 7) {
1976 FOREACH_MOD OnUserQuit(user);
1977 WriteCommonExcept(user,"QUIT :%s",reason);
1979 // Q token must go to ALL servers!!!
1980 char buffer[MAXBUF];
1981 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1982 NetSendToAll(buffer);
1985 /* push the socket on a stack of sockets due to be closed at the next opportunity
1986 * 'Client exited' is an exception to this as it means the client side has already
1987 * closed the socket, we don't need to do it.
1989 fd_reap.push_back(user->fd);
1991 bool do_purge = false;
1993 if (user->registered == 7) {
1994 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1998 if (iter != clientlist.end())
2000 log(DEBUG,"deleting user hash value %d",iter->second);
2001 if ((iter->second) && (user->registered == 7)) {
2002 if (iter->second) delete iter->second;
2004 clientlist.erase(iter);
2007 if (user->registered == 7) {
2008 purge_empty_chans();
2013 void kill_link_silent(userrec *user,const char* r)
2015 user_hash::iterator iter = clientlist.find(user->nick);
2017 char reason[MAXBUF];
2019 strncpy(reason,r,MAXBUF);
2021 if (strlen(reason)>MAXQUIT)
2023 reason[MAXQUIT-1] = '\0';
2026 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2027 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2028 log(DEBUG,"closing fd %d",user->fd);
2030 /* bugfix, cant close() a nonblocking socket (sux!) */
2031 if (user->registered == 7) {
2032 FOREACH_MOD OnUserQuit(user);
2033 WriteCommonExcept(user,"QUIT :%s",reason);
2035 // Q token must go to ALL servers!!!
2036 char buffer[MAXBUF];
2037 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2038 NetSendToAll(buffer);
2041 /* push the socket on a stack of sockets due to be closed at the next opportunity
2042 * 'Client exited' is an exception to this as it means the client side has already
2043 * closed the socket, we don't need to do it.
2045 fd_reap.push_back(user->fd);
2047 bool do_purge = false;
2049 if (iter != clientlist.end())
2051 log(DEBUG,"deleting user hash value %d",iter->second);
2052 if ((iter->second) && (user->registered == 7)) {
2053 if (iter->second) delete iter->second;
2055 clientlist.erase(iter);
2058 if (user->registered == 7) {
2059 purge_empty_chans();
2065 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2067 char* Passwd(userrec *user)
2069 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2071 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2079 bool IsDenied(userrec *user)
2081 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2083 if (match(user->host,i->host) && (i->type == CC_DENY))
2094 /* sends out an error notice to all connected clients (not to be used
2097 void send_error(char *s)
2099 log(DEBUG,"send_error: %s",s);
2100 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2102 if (isnick(i->second->nick))
2104 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2108 // fix - unregistered connections receive ERROR, not NOTICE
2109 Write(i->second->fd,"ERROR :%s",s);
2114 void Error(int status)
2116 signal (SIGALRM, SIG_IGN);
2117 signal (SIGPIPE, SIG_IGN);
2118 signal (SIGTERM, SIG_IGN);
2119 signal (SIGABRT, SIG_IGN);
2120 signal (SIGSEGV, SIG_IGN);
2121 signal (SIGURG, SIG_IGN);
2122 signal (SIGKILL, SIG_IGN);
2123 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
2124 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2129 int main(int argc, char **argv)
2133 log(DEBUG,"*** InspIRCd starting up!");
2134 if (!FileExists(CONFIG_FILE))
2136 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2137 log(DEFAULT,"main: no config");
2138 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2142 for (int i = 1; i < argc; i++)
2144 if (!strcmp(argv[i],"-nofork")) {
2147 if (!strcmp(argv[i],"-wait")) {
2152 strlcpy(MyExecutable,argv[0],MAXBUF);
2154 if (InspIRCd() == ERROR)
2156 log(DEFAULT,"main: daemon function bailed");
2157 printf("ERROR: could not initialise. Shutting down.\n");
2164 template<typename T> inline string ConvToStr(const T &in)
2167 if (!(tmp << in)) return string();
2171 /* re-allocates a nick in the user_hash after they change nicknames,
2172 * returns a pointer to the new user as it may have moved */
2174 userrec* ReHashNick(char* Old, char* New)
2176 user_hash::iterator newnick;
2177 user_hash::iterator oldnick = clientlist.find(Old);
2179 log(DEBUG,"ReHashNick: %s %s",Old,New);
2181 if (!strcasecmp(Old,New))
2183 log(DEBUG,"old nick is new nick, skipping");
2184 return oldnick->second;
2187 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2189 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2191 clientlist[New] = new userrec();
2192 clientlist[New] = oldnick->second;
2193 clientlist.erase(oldnick);
2195 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2197 return clientlist[New];
2200 /* adds or updates an entry in the whowas list */
2201 void AddWhoWas(userrec* u)
2203 user_hash::iterator iter = whowas.find(u->nick);
2204 userrec *a = new userrec();
2205 strlcpy(a->nick,u->nick,NICKMAX);
2206 strlcpy(a->ident,u->ident,64);
2207 strlcpy(a->dhost,u->dhost,256);
2208 strlcpy(a->host,u->host,256);
2209 strlcpy(a->fullname,u->fullname,128);
2210 strlcpy(a->server,u->server,256);
2211 a->signon = u->signon;
2213 /* MAX_WHOWAS: max number of /WHOWAS items
2214 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2215 * can be replaced by a newer one
2218 if (iter == whowas.end())
2220 if (whowas.size() == WHOWAS_MAX)
2222 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2224 // 3600 seconds in an hour ;)
2225 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
2227 if (i->second) delete i->second;
2229 log(DEBUG,"added WHOWAS entry, purged an old record");
2236 log(DEBUG,"added fresh WHOWAS entry");
2237 whowas[a->nick] = a;
2242 log(DEBUG,"updated WHOWAS entry");
2243 if (iter->second) delete iter->second;
2249 /* add a client connection to the sockets list */
2250 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2254 char resolved[MAXBUF];
2257 user_hash::iterator iter;
2259 tempnick = ConvToStr(socket) + "-unknown";
2260 sprintf(tn2,"%d-unknown",socket);
2262 iter = clientlist.find(tempnick);
2264 if (iter != clientlist.end()) return;
2267 * It is OK to access the value here this way since we know
2268 * it exists, we just created it above.
2270 * At NO other time should you access a value in a map or a
2271 * hash_map this way.
2273 clientlist[tempnick] = new userrec();
2275 NonBlocking(socket);
2276 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2278 clientlist[tempnick]->fd = socket;
2279 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2280 strncpy(clientlist[tempnick]->host, host,160);
2281 strncpy(clientlist[tempnick]->dhost, host,160);
2282 strncpy(clientlist[tempnick]->server, ServerName,256);
2283 strncpy(clientlist[tempnick]->ident, "unknown",9);
2284 clientlist[tempnick]->registered = 0;
2285 clientlist[tempnick]->signon = TIME+dns_timeout;
2286 clientlist[tempnick]->nping = TIME+240+dns_timeout;
2287 clientlist[tempnick]->lastping = 1;
2288 clientlist[tempnick]->port = port;
2289 strncpy(clientlist[tempnick]->ip,ip,32);
2291 // set the registration timeout for this user
2292 unsigned long class_regtimeout = 90;
2293 int class_flood = 0;
2295 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2297 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2299 class_regtimeout = (unsigned long)i->registration_timeout;
2300 class_flood = i->flood;
2305 clientlist[tempnick]->timeout = TIME+class_regtimeout;
2306 clientlist[tempnick]->flood = class_flood;
2308 for (int i = 0; i < MAXCHANS; i++)
2310 clientlist[tempnick]->chans[i].channel = NULL;
2311 clientlist[tempnick]->chans[i].uc_modes = 0;
2314 if (clientlist.size() == MAXCLIENTS)
2315 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2318 char* e = matches_exception(ip);
2321 char* r = matches_zline(ip);
2324 char reason[MAXBUF];
2325 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2326 kill_link(clientlist[tempnick],reason);
2331 // this function counts all users connected, wether they are registered or NOT.
2334 return clientlist.size();
2337 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
2338 int registered_usercount(void)
2341 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2343 if ((i->second->fd) && (isnick(i->second->nick))) c++;
2348 int usercount_invisible(void)
2352 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2354 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2359 int usercount_opers(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,'o'))) c++;
2370 int usercount_unknown(void)
2374 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2376 if ((i->second->fd) && (i->second->registered != 7))
2382 long chancount(void)
2384 return chanlist.size();
2387 long count_servs(void)
2390 //for (int j = 0; j < 255; j++)
2392 // if (servers[j] != NULL)
2398 long servercount(void)
2400 return count_servs()+1;
2406 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2408 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2414 void ShowMOTD(userrec *user)
2416 std::string WholeMOTD = "";
2419 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2422 WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2423 for (int i = 0; i != MOTD.size(); i++)
2425 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2427 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2428 // only one write operation
2429 send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
2433 void ShowRULES(userrec *user)
2437 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2440 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2441 for (int i = 0; i != RULES.size(); i++)
2443 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2445 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2448 /* shows the message of the day, and any other on-logon stuff */
2449 void FullConnectUser(userrec* user)
2451 user->registered = 7;
2452 user->idle_lastmsg = TIME;
2453 log(DEBUG,"ConnectUser: %s",user->nick);
2455 if (strcmp(Passwd(user),"") && (!user->haspassed))
2457 kill_link(user,"Invalid password");
2462 kill_link(user,"Unauthorised connection");
2466 char match_against[MAXBUF];
2467 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2468 char* e = matches_exception(match_against);
2471 char* r = matches_gline(match_against);
2474 char reason[MAXBUF];
2475 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2476 kill_link_silent(user,reason);
2479 r = matches_kline(user->host);
2482 char reason[MAXBUF];
2483 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2484 kill_link_silent(user,reason);
2489 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2490 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2491 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2492 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2493 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2494 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2495 std::stringstream v;
2496 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2497 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2498 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2499 v << std::string(Network);
2500 std::string data005 = v.str();
2501 FOREACH_MOD On005Numeric(data005);
2502 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2503 // so i'd better split it :)
2504 std::stringstream out(data005);
2505 std::string token = "";
2506 std::string line5 = "";
2507 int token_counter = 0;
2511 line5 = line5 + token + " ";
2513 if ((token_counter >= 13) || (out.eof() == true))
2515 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2521 FOREACH_MOD OnUserConnect(user);
2522 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2524 char buffer[MAXBUF];
2525 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);
2526 NetSendToAll(buffer);
2529 /* shows the message of the day, and any other on-logon stuff */
2530 void ConnectUser(userrec *user)
2532 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2533 if ((user->dns_done) && (user->registered >= 3))
2535 FullConnectUser(user);
2539 void handle_version(char **parameters, int pcnt, userrec *user)
2541 char Revision[] = "$Revision$";
2543 char *s1 = Revision;
2545 char *v1 = strtok_r(s1," ",&savept);
2547 char *v2 = strtok_r(s1," ",&savept);
2550 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2554 // calls a handler function for a command
2556 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2558 for (int i = 0; i < cmdlist.size(); i++)
2560 if (!strcasecmp(cmdlist[i].command,commandname))
2562 if (cmdlist[i].handler_function)
2564 if (pcnt>=cmdlist[i].min_params)
2566 if (strchr(user->modes,cmdlist[i].flags_needed))
2568 cmdlist[i].handler_function(parameters,pcnt,user);
2576 void DoSplitEveryone()
2578 bool go_again = true;
2582 for (int i = 0; i < 32; i++)
2586 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2588 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2591 j->CloseConnection();
2592 me[i]->connectors.erase(j);
2600 log(DEBUG,"Removed server. Will remove clients...");
2601 // iterate through the userlist and remove all users on this server.
2602 // because we're dealing with a mesh, we dont have to deal with anything
2603 // "down-route" from this server (nice huh)
2605 char reason[MAXBUF];
2609 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2611 if (strcasecmp(u->second->server,ServerName))
2613 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2614 kill_link(u->second,reason);
2624 char islast(const char* s)
2627 for (int j = 0; j < 32; j++)
2631 for (int k = 0; k < me[j]->connectors.size(); k++)
2633 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2637 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2647 long map_count(const char* s)
2650 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2652 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2658 void force_nickchange(userrec* user,const char* newnick)
2665 FOREACH_RESULT(OnUserPreNick(user,newnick));
2667 kill_link(user,"Nickname collision");
2670 if (matches_qline(newnick))
2672 kill_link(user,"Nickname collision");
2680 strncpy(nick,newnick,MAXBUF);
2682 if (user->registered == 7)
2686 handle_nick(pars,1,user);
2692 int process_parameters(char **command_p,char *parameters)
2697 q = strlen(parameters);
2700 /* no parameters, command_p invalid! */
2703 if (parameters[0] == ':')
2705 command_p[0] = parameters+1;
2710 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2712 /* only one parameter */
2713 command_p[0] = parameters;
2714 if (parameters[0] == ':')
2716 if (strchr(parameters,' ') != NULL)
2724 command_p[j++] = parameters;
2725 for (int i = 0; i <= q; i++)
2727 if (parameters[i] == ' ')
2729 command_p[j++] = parameters+i+1;
2730 parameters[i] = '\0';
2731 if (command_p[j-1][0] == ':')
2733 *command_p[j-1]++; /* remove dodgy ":" */
2735 /* parameter like this marks end of the sequence */
2739 return j; /* returns total number of items in the list */
2742 void process_command(userrec *user, char* cmd)
2746 char *command_p[127];
2747 char p[MAXBUF], temp[MAXBUF];
2748 int i, j, items, cmd_found;
2750 for (int i = 0; i < 127; i++)
2751 command_p[i] = NULL;
2761 if (!strcmp(cmd,""))
2766 int total_params = 0;
2769 for (int q = 0; q < strlen(cmd)-1; q++)
2771 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2774 // found a 'trailing', we dont count them after this.
2782 // another phidjit bug...
2783 if (total_params > 126)
2785 //kill_link(user,"Protocol violation (1)");
2786 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2790 strlcpy(temp,cmd,MAXBUF);
2792 std::string tmp = cmd;
2793 for (int i = 0; i <= MODCOUNT; i++)
2795 std::string oldtmp = tmp;
2796 modules[i]->OnServerRaw(tmp,true,user);
2799 log(DEBUG,"A Module changed the input string!");
2800 log(DEBUG,"New string: %s",tmp.c_str());
2801 log(DEBUG,"Old string: %s",oldtmp.c_str());
2805 strlcpy(cmd,tmp.c_str(),MAXBUF);
2806 strlcpy(temp,cmd,MAXBUF);
2808 if (!strchr(cmd,' '))
2810 /* no parameters, lets skip the formalities and not chop up
2812 log(DEBUG,"About to preprocess command with no params");
2814 command_p[0] = NULL;
2816 for (int i = 0; i <= strlen(cmd); i++)
2818 cmd[i] = toupper(cmd[i]);
2820 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2827 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2828 for (int i = 0; i < strlen(temp); i++)
2830 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2836 /* split the full string into a command plus parameters */
2840 if (strchr(cmd,' '))
2842 for (int i = 0; i <= strlen(cmd); i++)
2844 /* capitalise the command ONLY, leave params intact */
2845 cmd[i] = toupper(cmd[i]);
2846 /* are we nearly there yet?! :P */
2850 parameters = cmd+i+1;
2858 for (int i = 0; i <= strlen(cmd); i++)
2860 cmd[i] = toupper(cmd[i]);
2867 if (strlen(command)>MAXCOMMAND)
2869 //kill_link(user,"Protocol violation (2)");
2870 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2874 for (int x = 0; x < strlen(command); x++)
2876 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2878 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2880 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2882 //kill_link(user,"Protocol violation (3)");
2883 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2890 for (int i = 0; i != cmdlist.size(); i++)
2892 if (strcmp(cmdlist[i].command,""))
2894 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2896 log(DEBUG,"Found matching command");
2900 if (strcmp(parameters,""))
2902 items = process_parameters(command_p,parameters);
2907 command_p[0] = NULL;
2913 command_p[0] = NULL;
2918 log(DEBUG,"Processing command");
2920 /* activity resets the ping pending timer */
2921 user->nping = TIME + 120;
2922 if ((items) < cmdlist[i].min_params)
2924 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2925 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2928 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2930 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2931 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2935 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2937 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2938 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2942 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2944 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2946 if ((!isnick(user->nick)) || (user->registered != 7))
2948 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2949 WriteServ(user->fd,"451 %s :You have not registered",command);
2953 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2955 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2956 if (cmdlist[i].handler_function)
2958 /* ikky /stats counters */
2963 user->bytes_in += strlen(temp);
2965 user->bytes_out+=strlen(temp);
2968 cmdlist[i].use_count++;
2969 cmdlist[i].total_bytes+=strlen(temp);
2972 /* WARNING: nothing may come after the
2973 * command handler call, as the handler
2974 * may free the user structure! */
2976 cmdlist[i].handler_function(command_p,items,user);
2982 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2983 WriteServ(user->fd,"451 %s :You have not registered",command);
2991 if ((!cmd_found) && (user))
2993 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2994 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2999 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
3002 /* create the command and push it onto the table */
3003 strlcpy(comm.command,cmd,MAXBUF);
3004 strlcpy(comm.source,source,MAXBUF);
3005 comm.handler_function = f;
3006 comm.flags_needed = flags;
3007 comm.min_params = minparams;
3009 comm.total_bytes = 0;
3010 cmdlist.push_back(comm);
3011 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
3014 bool removecommands(const char* source)
3016 bool go_again = true;
3020 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
3022 if (!strcmp(i->source,source))
3024 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
3034 void SetupCommandTable(void)
3036 createcommand("USER",handle_user,0,4,"<core>");
3037 createcommand("NICK",handle_nick,0,1,"<core>");
3038 createcommand("QUIT",handle_quit,0,0,"<core>");
3039 createcommand("VERSION",handle_version,0,0,"<core>");
3040 createcommand("PING",handle_ping,0,1,"<core>");
3041 createcommand("PONG",handle_pong,0,1,"<core>");
3042 createcommand("ADMIN",handle_admin,0,0,"<core>");
3043 createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
3044 createcommand("INFO",handle_info,0,0,"<core>");
3045 createcommand("TIME",handle_time,0,0,"<core>");
3046 createcommand("WHOIS",handle_whois,0,1,"<core>");
3047 createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
3048 createcommand("NOTICE",handle_notice,0,2,"<core>");
3049 createcommand("JOIN",handle_join,0,1,"<core>");
3050 createcommand("NAMES",handle_names,0,1,"<core>");
3051 createcommand("PART",handle_part,0,1,"<core>");
3052 createcommand("KICK",handle_kick,0,2,"<core>");
3053 createcommand("MODE",handle_mode,0,1,"<core>");
3054 createcommand("TOPIC",handle_topic,0,1,"<core>");
3055 createcommand("WHO",handle_who,0,1,"<core>");
3056 createcommand("MOTD",handle_motd,0,0,"<core>");
3057 createcommand("RULES",handle_rules,0,0,"<core>");
3058 createcommand("OPER",handle_oper,0,2,"<core>");
3059 createcommand("LIST",handle_list,0,0,"<core>");
3060 createcommand("DIE",handle_die,'o',1,"<core>");
3061 createcommand("RESTART",handle_restart,'o',1,"<core>");
3062 createcommand("KILL",handle_kill,'o',2,"<core>");
3063 createcommand("REHASH",handle_rehash,'o',0,"<core>");
3064 createcommand("LUSERS",handle_lusers,0,0,"<core>");
3065 createcommand("STATS",handle_stats,0,1,"<core>");
3066 createcommand("USERHOST",handle_userhost,0,1,"<core>");
3067 createcommand("AWAY",handle_away,0,0,"<core>");
3068 createcommand("ISON",handle_ison,0,0,"<core>");
3069 createcommand("SUMMON",handle_summon,0,0,"<core>");
3070 createcommand("USERS",handle_users,0,0,"<core>");
3071 createcommand("INVITE",handle_invite,0,2,"<core>");
3072 createcommand("PASS",handle_pass,0,1,"<core>");
3073 createcommand("TRACE",handle_trace,'o',0,"<core>");
3074 createcommand("WHOWAS",handle_whowas,0,1,"<core>");
3075 createcommand("CONNECT",handle_connect,'o',1,"<core>");
3076 createcommand("SQUIT",handle_squit,'o',0,"<core>");
3077 createcommand("MODULES",handle_modules,0,0,"<core>");
3078 createcommand("LINKS",handle_links,0,0,"<core>");
3079 createcommand("MAP",handle_map,0,0,"<core>");
3080 createcommand("KLINE",handle_kline,'o',1,"<core>");
3081 createcommand("GLINE",handle_gline,'o',1,"<core>");
3082 createcommand("ZLINE",handle_zline,'o',1,"<core>");
3083 createcommand("QLINE",handle_qline,'o',1,"<core>");
3084 createcommand("ELINE",handle_eline,'o',1,"<core>");
3085 createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
3086 createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
3087 createcommand("SERVER",handle_server,0,0,"<core>");
3090 void process_buffer(const char* cmdbuf,userrec *user)
3094 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3101 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3104 if (!strcmp(cmdbuf,""))
3108 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3110 strlcpy(cmd,cmdbuf,MAXBUF);
3111 if (!strcmp(cmd,""))
3115 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3117 cmd[strlen(cmd)-1] = '\0';
3119 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3121 cmd[strlen(cmd)-1] = '\0';
3124 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3126 cmd[strlen(cmd)-1] = '\0';
3129 if (!strcmp(cmd,""))
3133 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3135 if ((user) && (cmd))
3137 process_command(user,cmd);
3141 void DoSync(serverrec* serv, char* tcp_host)
3144 log(DEBUG,"Sending sync");
3145 // send start of sync marker: Y <timestamp>
3146 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3147 // except the ones its receiving it from.
3148 snprintf(data,MAXBUF,"Y %d",TIME);
3149 serv->SendPacket(data,tcp_host);
3150 // send users and channels
3151 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3153 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);
3154 serv->SendPacket(data,tcp_host);
3155 if (strchr(u->second->modes,'o'))
3157 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3158 serv->SendPacket(data,tcp_host);
3160 for (int i = 0; i <= MODCOUNT; i++)
3162 string_list l = modules[i]->OnUserSync(u->second);
3163 for (int j = 0; j < l.size(); j++)
3165 strlcpy(data,l[j].c_str(),MAXBUF);
3166 serv->SendPacket(data,tcp_host);
3169 if (strcmp(chlist(u->second),""))
3171 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3172 serv->SendPacket(data,tcp_host);
3175 // send channel modes, topics etc...
3176 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3178 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3179 serv->SendPacket(data,tcp_host);
3180 for (int i = 0; i <= MODCOUNT; i++)
3182 string_list l = modules[i]->OnChannelSync(c->second);
3183 for (int j = 0; j < l.size(); j++)
3185 strlcpy(data,l[j].c_str(),MAXBUF);
3186 serv->SendPacket(data,tcp_host);
3189 if (strcmp(c->second->topic,""))
3191 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3192 serv->SendPacket(data,tcp_host);
3194 // send current banlist
3196 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3198 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3199 serv->SendPacket(data,tcp_host);
3202 // sync global zlines, glines, etc
3203 sync_xlines(serv,tcp_host);
3205 for (int j = 0; j < 32; j++)
3209 for (int k = 0; k < me[j]->connectors.size(); k++)
3211 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3213 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3214 serv->SendPacket(data,tcp_host);
3215 NetSendMyRoutingTable();
3221 snprintf(data,MAXBUF,"F %d",TIME);
3222 serv->SendPacket(data,tcp_host);
3223 log(DEBUG,"Sent sync");
3224 // ircd sends its serverlist after the end of sync here
3228 void NetSendMyRoutingTable()
3230 // send out a line saying what is reachable to us.
3231 // E.g. if A is linked to B C and D, send out:
3233 // if its only linked to B and D send out:
3235 // if it has no links, dont even send out the line at all.
3236 char buffer[MAXBUF];
3237 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3238 bool sendit = false;
3239 for (int i = 0; i < 32; i++)
3243 for (int j = 0; j < me[i]->connectors.size(); j++)
3245 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3247 strlcat(buffer," ",MAXBUF);
3248 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3255 NetSendToAll(buffer);
3259 void DoSplit(const char* params)
3261 bool go_again = true;
3265 for (int i = 0; i < 32; i++)
3269 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3271 if (!strcasecmp(j->GetServerName().c_str(),params))
3274 j->CloseConnection();
3275 me[i]->connectors.erase(j);
3283 log(DEBUG,"Removed server. Will remove clients...");
3284 // iterate through the userlist and remove all users on this server.
3285 // because we're dealing with a mesh, we dont have to deal with anything
3286 // "down-route" from this server (nice huh)
3288 char reason[MAXBUF];
3289 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3293 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3295 if (!strcasecmp(u->second->server,params))
3297 kill_link(u->second,reason);
3305 // removes a server. Will NOT remove its users!
3307 void RemoveServer(const char* name)
3309 bool go_again = true;
3313 for (int i = 0; i < 32; i++)
3317 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3319 if (!strcasecmp(j->GetServerName().c_str(),name))
3322 j->CloseConnection();
3323 me[i]->connectors.erase(j);
3334 int reap_counter = 0;
3335 char MODERR[MAXBUF];
3342 bool UnloadModule(const char* filename)
3344 for (int j = 0; j != module_names.size(); j++)
3346 if (module_names[j] == std::string(filename))
3348 if (modules[j]->GetVersion().Flags & VF_STATIC)
3350 log(DEFAULT,"Failed to unload STATIC module %s",filename);
3351 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
3355 log(DEBUG,"Deleting module...");
3358 log(DEBUG,"Deleting module factory pointer...");
3359 delete factory[j]->factory;
3360 log(DEBUG,"Deleting module factory...");
3362 log(DEBUG,"Erasing module entry...");
3364 // here we should locate ALL resources claimed by this module... and release them
3365 // for example commands
3366 log(DEBUG,"Erasing module vector...");
3367 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
3375 log(DEBUG,"Erasing module name vector...");
3376 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
3378 if (*v == std::string(filename))
3380 module_names.erase(v);
3384 log(DEBUG,"Erasing module pointer...");
3385 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
3393 log(DEBUG,"Removing dependent commands...");
3394 removecommands(filename);
3395 log(DEFAULT,"Module %s unloaded",filename);
3400 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
3401 snprintf(MODERR,MAXBUF,"Module not loaded");
3405 bool DirValid(char* dirandfile)
3408 strlcpy(work,dirandfile,MAXBUF);
3409 int p = strlen(work);
3410 // we just want the dir
3411 while (strlen(work))
3420 log(DEBUG,"Dir valid: %s",work);
3421 char buffer[MAXBUF], otherdir[MAXBUF];
3422 // Get the current working directory
3423 if( getcwd( buffer, MAXBUF ) == NULL )
3426 if( getcwd( otherdir, MAXBUF ) == NULL )
3429 log(DEBUG,"Dir is really: %s",otherdir);
3430 if (strlen(otherdir) >= strlen(work))
3432 otherdir[strlen(work)] = '\0';
3433 log(DEBUG,"Compare: '%s' -> '%s'",otherdir,work);
3434 if (!strcmp(otherdir,work))
3436 log(DEBUG,"Match ok");
3439 log(DEBUG,"No match");
3445 bool LoadModule(const char* filename)
3447 char modfile[MAXBUF];
3448 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,filename);
3449 if (!DirValid(modfile))
3451 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
3452 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
3455 log(DEBUG,"Loading module: %s",modfile);
3456 if (FileExists(modfile))
3458 for (int j = 0; j < module_names.size(); j++)
3460 if (module_names[j] == std::string(filename))
3462 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
3463 snprintf(MODERR,MAXBUF,"Module already loaded");
3467 factory[MODCOUNT+1] = new ircd_module(modfile);
3468 if (factory[MODCOUNT+1]->LastError())
3470 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
3471 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
3475 if (factory[MODCOUNT+1]->factory)
3477 modules[MODCOUNT+1] = factory[MODCOUNT+1]->factory->CreateModule();
3478 /* save the module and the module's classfactory, if
3479 * this isnt done, random crashes can occur :/ */
3480 module_names.push_back(filename);
3484 log(DEFAULT,"Unable to load %s",modfile);
3485 snprintf(MODERR,MAXBUF,"Factory function failed!");
3491 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
3492 snprintf(MODERR,MAXBUF,"Module file could not be found");
3501 struct sockaddr_in client,server;
3502 char addrs[MAXBUF][255];
3503 int incomingSockfd, result = TRUE;
3506 int selectResult = 0, selectResult2 = 0;
3507 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3508 char resolvedHost[MAXBUF];
3512 log_file = fopen("ircd.log","a+");
3515 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3519 log(DEBUG,"InspIRCd: startup: begin");
3523 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3525 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
3527 SetupCommandTable();
3528 log(DEBUG,"InspIRCd: startup: default command table set up");
3530 ReadConfig(true,NULL);
3531 if (strcmp(DieValue,""))
3533 printf("WARNING: %s\n\n",DieValue);
3534 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3537 log(DEBUG,"InspIRCd: startup: read config");
3539 int count2 = 0, count3 = 0;
3541 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3543 ConfValue("bind","port",count,configToken,&config_f);
3544 ConfValue("bind","address",count,Addr,&config_f);
3545 ConfValue("bind","type",count,Type,&config_f);
3546 if (!strcmp(Type,"servers"))
3548 char Default[MAXBUF];
3549 strcpy(Default,"no");
3550 ConfValue("bind","default",count,Default,&config_f);
3551 if (strchr(Default,'y'))
3553 defaultRoute = count3;
3554 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3556 me[count3] = new serverrec(ServerName,100L,false);
3557 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3559 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3568 ports[count2] = atoi(configToken);
3569 strlcpy(addrs[count2],Addr,256);
3572 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3575 UDPportCount = count3;
3577 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3579 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3583 /* BugFix By Craig! :p */
3585 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3587 ConfValue("module","name",count2,configToken,&config_f);
3588 printf("Loading module... \033[1;37m%s\033[0;37m\n",configToken);
3589 if (!LoadModule(configToken))
3591 log(DEBUG,"Exiting due to a module loader error.");
3592 printf("There was an error loading a module: %s\n",ModuleError());
3596 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3598 printf("\nInspIRCd is now running!\n");
3600 startup_time = time(NULL);
3604 log(VERBOSE,"Not forking as -nofork was specified");
3608 if (DaemonSeed() == ERROR)
3610 log(DEFAULT,"InspIRCd: startup: can't daemonise");
3611 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3617 ConfValue("pid","file",0,PID,&config_f);
3621 /* setup select call */
3622 FD_ZERO(&selectFds);
3623 log(DEBUG,"InspIRCd: startup: zero selects");
3624 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3626 for (count = 0; count < portCount; count++)
3628 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3630 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3633 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3635 log(DEFAULT,"InspIRCd: startup: failed to bind port %d",ports[count]);
3637 else /* well we at least bound to one socket so we'll continue */
3643 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3645 /* if we didn't bind to anything then abort */
3646 if (boundPortCount == 0)
3648 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
3653 length = sizeof (client);
3654 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3658 tvs.tv_usec = 7000L;
3665 tval.tv_usec = 7000L;
3667 int total_in_this_set = 0;
3669 bool expire_run = false;
3671 /* main loop, this never returns */
3674 #ifdef _POSIX_PRIORITY_SCHEDULING
3681 // we only read time() once per iteration rather than tons of times!
3684 user_hash::iterator count2 = clientlist.begin();
3686 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3687 // them in a list, then reap the list every second or so.
3688 if (((TIME % 5) == 0) && (!expire_run))
3693 if ((TIME % 5) == 1)
3695 if (reap_counter>300)
3697 if (fd_reap.size() > 0)
3699 for( int n = 0; n < fd_reap.size(); n++)
3701 //Blocking(fd_reap[n]);
3703 shutdown (fd_reap[n],2);
3704 //NonBlocking(fd_reap[n]);
3712 FD_ZERO(&serverfds);
3714 for (int x = 0; x != UDPportCount; x++)
3717 FD_SET(me[x]->fd, &serverfds);
3720 // serverFds timevals went here
3722 tvs.tv_usec = 7000L;
3723 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3726 for (int x = 0; x != UDPportCount; x++)
3728 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3730 char remotehost[MAXBUF],resolved[MAXBUF];
3731 length = sizeof (client);
3732 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3733 if (incomingSockfd != -1)
3735 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3736 if(CleanAndResolve(resolved, remotehost) != TRUE)
3738 strlcpy(resolved,remotehost,MAXBUF);
3740 // add to this connections ircd_connector vector
3741 // *FIX* - we need the LOCAL port not the remote port in &client!
3742 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3748 for (int x = 0; x < UDPportCount; x++)
3750 std::deque<std::string> msgs;
3752 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3754 for (int ctr = 0; ctr < msgs.size(); ctr++)
3756 char udp_msg[MAXBUF];
3757 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3758 if (strlen(udp_msg)<1)
3760 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3763 // during a netburst, send all data to all other linked servers
3764 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3766 if (is_uline(tcp_host))
3768 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3770 NetSendToAllExcept(tcp_host,udp_msg);
3774 NetSendToAllExcept(tcp_host,udp_msg);
3776 FOREACH_MOD OnPacketReceive(udp_msg);
3777 handle_link_packet(udp_msg, tcp_host, me[x]);
3784 while (count2 != clientlist.end())
3787 total_in_this_set = 0;
3789 user_hash::iterator xcount = count2;
3790 user_hash::iterator endingiter = count2;
3792 if (count2 == clientlist.end()) break;
3795 if (count2->second->fd != 0)
3797 // assemble up to 64 sockets into an fd_set
3798 // to implement a pooling mechanism.
3800 // This should be up to 64x faster than the
3801 // old implementation.
3802 while (total_in_this_set < 64)
3804 if (count2 != clientlist.end())
3806 // we don't check the state of remote users.
3807 if (count2->second->fd > 0)
3809 FD_SET (count2->second->fd, &sfd);
3811 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3812 // their connection class.
3813 if ((TIME > count2->second->timeout) && (count2->second->registered != 7))
3815 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3816 kill_link(count2->second,"Registration timeout");
3819 if ((TIME > count2->second->signon) && (count2->second->registered == 3))
3821 count2->second->dns_done = true;
3822 FullConnectUser(count2->second);
3825 if ((count2->second->dns_done) && (count2->second->registered == 3)) // both NICK and USER... and DNS
3827 FullConnectUser(count2->second);
3830 if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3832 if ((!count2->second->lastping) && (count2->second->registered == 7))
3834 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3835 kill_link(count2->second,"Ping timeout");
3838 Write(count2->second->fd,"PING :%s",ServerName);
3839 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3840 count2->second->lastping = 0;
3841 count2->second->nping = TIME+120;
3845 total_in_this_set++;
3850 endingiter = count2;
3851 count2 = xcount; // roll back to where we were
3855 // tvals defined here
3857 tval.tv_usec = 7000L;
3858 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3860 // now loop through all of the items in this pool if any are waiting
3861 //if (selectResult2 > 0)
3862 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3865 #ifdef _POSIX_PRIORITY_SCHEDULING
3870 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3872 memset(data, 0, 10240);
3873 result = read(count2a->second->fd, data, 10240);
3877 userrec* current = count2a->second;
3878 int currfd = current->fd;
3879 char* l = strtok(data,"\n");
3884 if ((floodlines > current->flood) && (current->flood != 0))
3886 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3887 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3888 kill_link(current,"Excess flood");
3891 char sanitized[NetBufferSize];
3892 memset(sanitized, 0, NetBufferSize);
3894 for (int pt = 0; pt < strlen(l); pt++)
3898 sanitized[ptt++] = l[pt];
3901 sanitized[ptt] = '\0';
3902 if (strlen(sanitized))
3906 // we're gonna re-scan to check if the nick is gone, after every
3907 // command - if it has, we're gonna bail
3908 bool find_again = false;
3909 process_buffer(sanitized,current);
3911 // look for the user's record in case it's changed
3912 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3914 if (c2->second->fd == currfd)
3916 // found again, update pointer
3917 current == c2->second;
3926 l = strtok(NULL,"\n");
3931 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3933 log(DEBUG,"killing: %s",count2a->second->nick);
3934 kill_link(count2a->second,strerror(errno));
3938 // result EAGAIN means nothing read
3939 if (result == EAGAIN)
3947 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3948 kill_link(count2a->second,"Client exited");
3949 // must bail here? kill_link removes the hash, corrupting the iterator
3950 log(DEBUG,"Bailing from client exit");
3954 else if (result > 0)
3959 for (int q = 0; q < total_in_this_set; q++)
3961 // there is no iterator += operator :(
3962 //if (count2 != clientlist.end())
3969 // set up select call
3970 for (count = 0; count < boundPortCount; count++)
3972 FD_SET (openSockfd[count], &selectFds);
3976 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3978 /* select is reporting a waiting socket. Poll them all to find out which */
3979 if (selectResult > 0)
3981 char target[MAXBUF], resolved[MAXBUF];
3982 for (count = 0; count < boundPortCount; count++)
3984 if (FD_ISSET (openSockfd[count], &selectFds))
3986 length = sizeof (client);
3987 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3989 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3990 strlcpy (resolved, target, MAXBUF);
3992 if (incomingSockfd < 0)
3994 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3995 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3999 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
4000 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4007 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
4010 close (incomingSockfd);