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 char DisabledCommands[MAXBUF];
94 bool AllowHalfop = true;
95 bool AllowProtect = true;
96 bool AllowFounder = true;
98 extern std::vector<Module*> modules;
99 std::vector<std::string> module_names;
100 extern std::vector<ircd_module*> factory;
101 std::vector<int> fd_reap;
104 int openSockfd[MAXSOCKS];
106 bool unlimitcore = false;
108 time_t TIME = time(NULL);
113 template<> struct hash<in_addr>
115 template<> struct nspace::hash<in_addr>
118 size_t operator()(const struct in_addr &a) const
121 memcpy(&q,&a,sizeof(size_t));
126 template<> struct hash<string>
128 template<> struct nspace::hash<string>
131 size_t operator()(const string &s) const
134 static struct hash<const char *> strhash;
135 strlcpy(a,s.c_str(),MAXBUF);
146 bool operator()(const string& s1, const string& s2) const
148 char a[MAXBUF],b[MAXBUF];
149 strlcpy(a,s1.c_str(),MAXBUF);
150 strlcpy(b,s2.c_str(),MAXBUF);
153 return (strcasecmp(a,b) == 0);
158 struct InAddr_HashComp
161 bool operator()(const in_addr &s1, const in_addr &s2) const
166 memcpy(&q,&s1,sizeof(size_t));
167 memcpy(&p,&s2,sizeof(size_t));
175 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
176 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
177 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
178 typedef std::deque<command_t> command_table;
184 user_hash clientlist;
187 command_table cmdlist;
194 struct linger linger = { 0 };
195 char MyExecutable[1024];
196 int boundPortCount = 0;
197 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
198 int defaultRoute = 0;
199 char ModPath[MAXBUF];
203 long MyKey = C.GenKey();
207 int has_channel(userrec *u, chanrec *c);
208 int usercount(chanrec *c);
209 int usercount_i(chanrec *c);
210 char* Passwd(userrec *user);
211 bool IsDenied(userrec *user);
212 void AddWhoWas(userrec* u);
214 std::vector<long> auth_cookies;
215 std::stringstream config_f(stringstream::in | stringstream::out);
221 char Revision[] = "$Revision$";
224 char *v1 = strtok_r(s1," ",&savept);
226 char *v2 = strtok_r(s1," ",&savept);
228 return (long)(atof(v2)*10000);
232 std::string getservername()
237 std::string getserverdesc()
242 std::string getnetworkname()
247 std::string getadminname()
252 std::string getadminemail()
257 std::string getadminnick()
262 void log(int level,char *text, ...)
264 char textbuffer[MAXBUF];
267 struct tm * timeinfo;
268 if (level < LogLevel)
272 timeinfo = localtime (&rawtime);
277 va_start (argsPtr, text);
278 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
280 strlcpy(b,asctime(timeinfo),MAXBUF);
281 b[strlen(b)-1] = ':';
282 fprintf(log_file,"%s %s\n",b,textbuffer);
285 // nofork enabled? display it on terminal too
286 printf("%s %s\n",b,textbuffer);
291 void readfile(file_cache &F, const char* fname)
294 char linebuf[MAXBUF];
296 log(DEBUG,"readfile: loading %s",fname);
298 file = fopen(fname,"r");
303 fgets(linebuf,sizeof(linebuf),file);
304 linebuf[strlen(linebuf)-1]='\0';
305 if (!strcmp(linebuf,""))
311 F.push_back(linebuf);
318 log(DEBUG,"readfile: failed to load file: %s",fname);
320 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
323 void ReadConfig(bool bail, userrec* user)
325 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
326 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF];
328 std::stringstream errstr;
330 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
335 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
343 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
344 while (!errstr.eof())
346 errstr.getline(dataline,1024);
347 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
352 WriteOpers("There were errors in the configuration file:",user->nick);
353 while (!errstr.eof())
355 errstr.getline(dataline,1024);
356 WriteOpers(dataline);
363 ConfValue("server","name",0,ServerName,&config_f);
364 ConfValue("server","description",0,ServerDesc,&config_f);
365 ConfValue("server","network",0,Network,&config_f);
366 ConfValue("admin","name",0,AdminName,&config_f);
367 ConfValue("admin","email",0,AdminEmail,&config_f);
368 ConfValue("admin","nick",0,AdminNick,&config_f);
369 ConfValue("files","motd",0,motd,&config_f);
370 ConfValue("files","rules",0,rules,&config_f);
371 ConfValue("power","diepass",0,diepass,&config_f);
372 ConfValue("power","pause",0,pauseval,&config_f);
373 ConfValue("power","restartpass",0,restartpass,&config_f);
374 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
375 ConfValue("die","value",0,DieValue,&config_f);
376 ConfValue("options","loglevel",0,dbg,&config_f);
377 ConfValue("options","netbuffersize",0,NB,&config_f);
378 ConfValue("options","maxwho",0,MW,&config_f);
379 ConfValue("options","allowhalfop",0,AH,&config_f);
380 ConfValue("options","allowprotect",0,AP,&config_f);
381 ConfValue("options","allowfounder",0,AF,&config_f);
382 ConfValue("dns","server",0,DNSServer,&config_f);
383 ConfValue("dns","timeout",0,DNT,&config_f);
384 ConfValue("options","moduledir",0,ModPath,&config_f);
385 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
387 NetBufferSize = atoi(NB);
388 MaxWhoResults = atoi(MW);
389 dns_timeout = atoi(DNT);
392 if (!strcmp(DNSServer,""))
393 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
394 if (!strcmp(ModPath,""))
395 strlcpy(ModPath,MOD_PATH,MAXBUF);
396 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
397 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
398 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
399 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
401 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
402 NetBufferSize = 10240;
404 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
406 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
409 if (!strcmp(dbg,"debug"))
411 if (!strcmp(dbg,"verbose"))
413 if (!strcmp(dbg,"default"))
415 if (!strcmp(dbg,"sparse"))
417 if (!strcmp(dbg,"none"))
420 log(DEFAULT,"Reading message of the day...");
421 readfile(RULES,rules);
422 log(DEFAULT,"Reading connect classes...");
424 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
427 ConfValue("connect","allow",i,Value,&config_f);
428 ConfValue("connect","timeout",i,timeout,&config_f);
429 ConfValue("connect","flood",i,flood,&config_f);
430 ConfValue("connect","pingfreq",i,pfreq,&config_f);
431 if (strcmp(Value,""))
433 strlcpy(c.host,Value,MAXBUF);
435 strlcpy(Value,"",MAXBUF);
436 ConfValue("connect","password",i,Value,&config_f);
437 strlcpy(c.pass,Value,MAXBUF);
438 c.registration_timeout = 90; // default is 2 minutes
440 c.flood = atoi(flood);
443 c.registration_timeout = atoi(timeout);
447 c.pingtime = atoi(pfreq);
449 Classes.push_back(c);
450 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
454 ConfValue("connect","deny",i,Value,&config_f);
455 strlcpy(c.host,Value,MAXBUF);
457 Classes.push_back(c);
458 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
462 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
463 read_xline_defaults();
464 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
466 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
469 log(DEFAULT,"Adding and removing modules due to rehash...");
471 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
473 // store the old module names
474 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
476 old_module_names.push_back(*t);
479 // get the new module names
480 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
482 ConfValue("module","name",count2,Value,&config_f);
483 new_module_names.push_back(Value);
486 // now create a list of new modules that are due to be loaded
487 // and a seperate list of modules which are due to be unloaded
488 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
491 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
497 added_modules.push_back(*_new);
499 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
502 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
508 removed_modules.push_back(*oldm);
510 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
512 int rem = 0, add = 0;
513 if (!removed_modules.empty())
514 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
516 if (UnloadModule(removing->c_str()))
518 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
519 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
524 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
527 if (!added_modules.empty())
528 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
530 if (LoadModule(adding->c_str()))
532 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
533 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
538 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
541 log(DEFAULT,"Successfully unloaded %d of %d modules and loaded %d of %d modules.",rem,removed_modules.size(),add,added_modules.size());
545 /* write formatted text to a socket, in same format as printf */
547 void Write(int sock,char *text, ...)
549 if (sock == FD_MAGIC_NUMBER)
553 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
556 char textbuffer[MAXBUF];
560 va_start (argsPtr, text);
561 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
563 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
567 write(sock,tb,strlen(tb));
571 /* write a server formatted numeric response to a single socket */
573 void WriteServ(int sock, char* text, ...)
575 if (sock == FD_MAGIC_NUMBER)
579 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
582 char textbuffer[MAXBUF],tb[MAXBUF];
584 va_start (argsPtr, text);
586 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
588 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
592 write(sock,tb,strlen(tb));
596 /* write text from an originating user to originating user */
598 void WriteFrom(int sock, userrec *user,char* text, ...)
600 if (sock == FD_MAGIC_NUMBER)
602 if ((!text) || (!user))
604 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
607 char textbuffer[MAXBUF],tb[MAXBUF];
609 va_start (argsPtr, text);
611 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
613 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
617 write(sock,tb,strlen(tb));
621 /* write text to an destination user from a source user (e.g. user privmsg) */
623 void WriteTo(userrec *source, userrec *dest,char *data, ...)
625 if ((!dest) || (!data))
627 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
630 if (dest->fd == FD_MAGIC_NUMBER)
632 char textbuffer[MAXBUF],tb[MAXBUF];
634 va_start (argsPtr, data);
635 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
639 // if no source given send it from the server.
642 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
646 WriteFrom(dest->fd,source,"%s",textbuffer);
650 /* write formatted text from a source user to all users on a channel
651 * including the sender (NOT for privmsg, notice etc!) */
653 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
655 if ((!Ptr) || (!user) || (!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 != FD_MAGIC_NUMBER)
670 WriteTo(user,i->second,"%s",textbuffer);
675 /* write formatted text from a source user to all users on a channel
676 * including the sender (NOT for privmsg, notice etc!) doesnt send to
677 * users on remote servers */
679 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
681 if ((!Ptr) || (!text))
683 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
686 char textbuffer[MAXBUF];
688 va_start (argsPtr, text);
689 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
691 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
693 if (has_channel(i->second,Ptr))
695 if ((i->second->fd != -1) && (i->second->fd != FD_MAGIC_NUMBER))
699 WriteServ(i->second->fd,"%s",textbuffer);
703 WriteTo(user,i->second,"%s",textbuffer);
711 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
713 if ((!Ptr) || (!user) || (!text))
715 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
718 char textbuffer[MAXBUF];
720 va_start (argsPtr, text);
721 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
723 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
727 if ((has_channel(i->second,Ptr)) && (i->second->fd != FD_MAGIC_NUMBER))
729 WriteServ(i->second->fd,"%s",textbuffer);
736 /* write formatted text from a source user to all users on a channel except
737 * for the sender (for privmsg etc) */
739 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
741 if ((!Ptr) || (!user) || (!text))
743 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
746 char textbuffer[MAXBUF];
748 va_start (argsPtr, text);
749 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
752 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
756 if ((has_channel(i->second,Ptr)) && (user != i->second) && (i->second->fd != FD_MAGIC_NUMBER))
758 WriteTo(user,i->second,"%s",textbuffer);
765 std::string GetServerDescription(char* servername)
767 for (int j = 0; j < 32; j++)
771 for (int k = 0; k < me[j]->connectors.size(); k++)
773 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
775 return me[j]->connectors[k].GetDescription();
779 return ServerDesc; // not a remote server that can be found, it must be me.
784 /* write a formatted string to all users who share at least one common
785 * channel, including the source user e.g. for use in NICK */
787 void WriteCommon(userrec *u, char* text, ...)
791 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
795 if (u->registered != 7) {
796 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
800 char textbuffer[MAXBUF];
802 va_start (argsPtr, text);
803 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
806 WriteFrom(u->fd,u,"%s",textbuffer);
808 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
812 if ((common_channels(u,i->second) && (i->second != u)) && (i->second->fd != FD_MAGIC_NUMBER))
814 WriteFrom(i->second->fd,u,"%s",textbuffer);
820 /* write a formatted string to all users who share at least one common
821 * channel, NOT including the source user e.g. for use in QUIT */
823 void WriteCommonExcept(userrec *u, char* text, ...)
827 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
831 if (u->registered != 7) {
832 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
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 ((common_channels(u,i->second)) && (u != i->second))
848 WriteFrom(i->second->fd,u,"%s",textbuffer);
854 void WriteOpers(char* text, ...)
858 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
862 char textbuffer[MAXBUF];
864 va_start (argsPtr, text);
865 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
868 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
870 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
872 if (strchr(i->second->modes,'o'))
874 if (strchr(i->second->modes,'s'))
876 // send server notices to all with +s
877 // (TODO: needs SNOMASKs)
878 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
885 // returns TRUE of any users on channel C occupy server 'servername'.
887 bool ChanAnyOnThisServer(chanrec *c,char* servername)
889 log(DEBUG,"ChanAnyOnThisServer");
890 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
892 if (has_channel(i->second,c))
894 if (!strcasecmp(i->second->server,servername))
903 // returns true if user 'u' shares any common channels with any users on server 'servername'
905 bool CommonOnThisServer(userrec* u,const char* servername)
907 log(DEBUG,"ChanAnyOnThisServer");
908 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
910 if ((common_channels(u,i->second)) && (u != i->second))
912 if (!strcasecmp(i->second->server,servername))
914 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
923 void NetSendToCommon(userrec* u, char* s)
926 snprintf(buffer,MAXBUF,"%s",s);
928 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
930 std::string msg = buffer;
931 FOREACH_MOD OnPacketTransmit(msg,s);
932 strlcpy(buffer,msg.c_str(),MAXBUF);
934 for (int j = 0; j < 32; j++)
938 for (int k = 0; k < me[j]->connectors.size(); k++)
940 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
942 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
950 void NetSendToAll(char* s)
953 snprintf(buffer,MAXBUF,"%s",s);
955 log(DEBUG,"NetSendToAll: '%s'",s);
957 std::string msg = buffer;
958 FOREACH_MOD OnPacketTransmit(msg,s);
959 strlcpy(buffer,msg.c_str(),MAXBUF);
961 for (int j = 0; j < 32; j++)
965 for (int k = 0; k < me[j]->connectors.size(); k++)
967 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
973 void NetSendToAllAlive(char* s)
976 snprintf(buffer,MAXBUF,"%s",s);
978 log(DEBUG,"NetSendToAllAlive: '%s'",s);
980 std::string msg = buffer;
981 FOREACH_MOD OnPacketTransmit(msg,s);
982 strlcpy(buffer,msg.c_str(),MAXBUF);
984 for (int j = 0; j < 32; j++)
988 for (int k = 0; k < me[j]->connectors.size(); k++)
990 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
992 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
996 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
1004 void NetSendToOne(char* target,char* s)
1006 char buffer[MAXBUF];
1007 snprintf(buffer,MAXBUF,"%s",s);
1009 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
1011 std::string msg = buffer;
1012 FOREACH_MOD OnPacketTransmit(msg,s);
1013 strlcpy(buffer,msg.c_str(),MAXBUF);
1015 for (int j = 0; j < 32; j++)
1019 for (int k = 0; k < me[j]->connectors.size(); k++)
1021 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1023 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1030 void NetSendToAllExcept(const char* target,char* s)
1032 char buffer[MAXBUF];
1033 snprintf(buffer,MAXBUF,"%s",s);
1035 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
1037 std::string msg = buffer;
1038 FOREACH_MOD OnPacketTransmit(msg,s);
1039 strlcpy(buffer,msg.c_str(),MAXBUF);
1041 for (int j = 0; j < 32; j++)
1045 for (int k = 0; k < me[j]->connectors.size(); k++)
1047 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1049 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1057 void WriteMode(const char* modes, int flags, const char* text, ...)
1059 if ((!text) || (!modes) || (!flags))
1061 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1065 char textbuffer[MAXBUF];
1067 va_start (argsPtr, text);
1068 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1071 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1073 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
1075 bool send_to_user = false;
1077 if (flags == WM_AND)
1079 send_to_user = true;
1080 for (int n = 0; n < strlen(modes); n++)
1082 if (!hasumode(i->second,modes[n]))
1084 send_to_user = false;
1089 else if (flags == WM_OR)
1091 send_to_user = false;
1092 for (int n = 0; n < strlen(modes); n++)
1094 if (hasumode(i->second,modes[n]))
1096 send_to_user = true;
1104 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1111 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1113 if ((!text) || (!source))
1115 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1120 char textbuffer[MAXBUF];
1122 va_start (argsPtr, text);
1123 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1126 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1128 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
1130 if (strchr(i->second->modes,'w'))
1132 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1139 char buffer[MAXBUF];
1140 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1141 NetSendToAll(buffer);
1145 /* convert a string to lowercase. Note following special circumstances
1146 * taken from RFC 1459. Many "official" server branches still hold to this
1147 * rule so i will too;
1149 * Because of IRC's scandanavian origin, the characters {}| are
1150 * considered to be the lower case equivalents of the characters []\,
1151 * respectively. This is a critical issue when determining the
1152 * equivalence of two nicknames.
1155 void strlower(char *n)
1161 for (int i = 0; i != strlen(n); i++)
1163 n[i] = tolower(n[i]);
1175 /* Find a user record by nickname and return a pointer to it */
1177 userrec* Find(std::string nick)
1179 user_hash::iterator iter = clientlist.find(nick);
1181 if (iter == clientlist.end())
1182 /* Couldn't find it */
1185 return iter->second;
1188 /* find a channel record by channel name and return a pointer to it */
1190 chanrec* FindChan(const char* chan)
1194 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1198 chan_hash::iterator iter = chanlist.find(chan);
1200 if (iter == chanlist.end())
1201 /* Couldn't find it */
1204 return iter->second;
1208 long GetMaxBans(char* name)
1211 for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1213 ConfValue("banlist","chan",count,CM,&config_f);
1216 ConfValue("banlist","limit",count,CM,&config_f);
1224 void purge_empty_chans(void)
1226 int go_again = 1, purge = 0;
1231 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1234 if (!usercount(i->second))
1236 /* kill the record */
1237 if (i != chanlist.end())
1239 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1250 log(DEBUG,"skipped purge for %s",i->second->name);
1255 log(DEBUG,"completed channel purge, killed %d",purge);
1259 char scratch[MAXBUF];
1260 char sparam[MAXBUF];
1262 char* chanmodes(chanrec *chan)
1266 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1273 if (chan->noexternal)
1275 strlcat(scratch,"n",MAXMODES);
1277 if (chan->topiclock)
1279 strlcat(scratch,"t",MAXMODES);
1281 if (strcmp(chan->key,""))
1283 strlcat(scratch,"k",MAXMODES);
1287 strlcat(scratch,"l",MAXMODES);
1289 if (chan->inviteonly)
1291 strlcat(scratch,"i",MAXMODES);
1293 if (chan->moderated)
1295 strlcat(scratch,"m",MAXMODES);
1299 strlcat(scratch,"s",MAXMODES);
1301 if (chan->c_private)
1303 strlcat(scratch,"p",MAXMODES);
1305 if (strcmp(chan->key,""))
1307 strlcat(sparam," ",MAXBUF);
1308 strlcat(sparam,chan->key,MAXBUF);
1313 sprintf(foo," %d",chan->limit);
1314 strlcat(sparam,foo,MAXBUF);
1316 if (strlen(chan->custom_modes))
1318 strlcat(scratch,chan->custom_modes,MAXMODES);
1319 for (int z = 0; z < strlen(chan->custom_modes); z++)
1321 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1324 strlcat(sparam," ",MAXBUF);
1325 strlcat(sparam,extparam.c_str(),MAXBUF);
1329 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1330 strlcat(scratch,sparam,MAXMODES);
1335 /* compile a userlist of a channel into a string, each nick seperated by
1336 * spaces and op, voice etc status shown as @ and + */
1338 void userlist(userrec *user,chanrec *c)
1340 if ((!c) || (!user))
1342 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1346 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1347 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1349 if (has_channel(i->second,c))
1351 if (isnick(i->second->nick))
1353 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1355 /* user is +i, and source not on the channel, does not show
1356 * nick in NAMES list */
1359 strlcat(list,cmode(i->second,c),MAXBUF);
1360 strlcat(list,i->second->nick,MAXBUF);
1361 strlcat(list," ",MAXBUF);
1362 if (strlen(list)>(480-NICKMAX))
1364 /* list overflowed into
1365 * multiple numerics */
1366 WriteServ(user->fd,"%s",list);
1367 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1372 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1374 WriteServ(user->fd,"%s",list);
1378 /* return a count of the users on a specific channel accounting for
1379 * invisible users who won't increase the count. e.g. for /LIST */
1381 int usercount_i(chanrec *c)
1388 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1393 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1397 if (has_channel(i->second,c))
1399 if (isnick(i->second->nick))
1401 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1403 /* user is +i, and source not on the channel, does not show
1404 * nick in NAMES list */
1412 log(DEBUG,"usercount_i: %s %d",c->name,count);
1417 int usercount(chanrec *c)
1424 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1429 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1433 if (has_channel(i->second,c))
1435 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1442 log(DEBUG,"usercount: %s %d",c->name,count);
1447 /* add a channel to a user, creating the record for it if needed and linking
1448 * it to the user record */
1450 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1452 if ((!user) || (!cn))
1454 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1463 strncpy(cname,cn,MAXBUF);
1465 // we MUST declare this wherever we use FOREACH_RESULT
1468 if (strlen(cname) > CHANMAX-1)
1470 cname[CHANMAX-1] = '\0';
1473 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1475 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1477 return NULL; // already on the channel!
1481 if (!FindChan(cname))
1484 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1485 if (MOD_RESULT == 1) {
1489 /* create a new one */
1490 log(DEBUG,"add_channel: creating: %s",cname);
1492 chanlist[cname] = new chanrec();
1494 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1495 chanlist[cname]->topiclock = 1;
1496 chanlist[cname]->noexternal = 1;
1497 chanlist[cname]->created = TIME;
1498 strcpy(chanlist[cname]->topic, "");
1499 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1500 chanlist[cname]->topicset = 0;
1501 Ptr = chanlist[cname];
1502 log(DEBUG,"add_channel: created: %s",cname);
1503 /* set created to 2 to indicate user
1504 * is the first in the channel
1505 * and should be given ops */
1511 /* channel exists, just fish out a pointer to its struct */
1512 Ptr = FindChan(cname);
1515 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1517 // the override flag allows us to bypass channel modes
1518 // and bans (used by servers)
1519 if ((!override) || (!strcasecmp(user->server,ServerName)))
1521 log(DEBUG,"Not overriding...");
1523 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1524 if (MOD_RESULT == 1) {
1527 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1531 log(DEBUG,"add_channel: checking key, invite, etc");
1533 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
1534 if (MOD_RESULT == 0)
1536 if (strcmp(Ptr->key,""))
1538 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1541 log(DEBUG,"add_channel: no key given in JOIN");
1542 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1547 if (strcasecmp(key,Ptr->key))
1549 log(DEBUG,"add_channel: bad key given in JOIN");
1550 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1555 log(DEBUG,"add_channel: no key");
1558 FOREACH_RESULT(OnCheckInvite(user, Ptr));
1559 if (MOD_RESULT == 0)
1561 if (Ptr->inviteonly)
1563 log(DEBUG,"add_channel: channel is +i");
1564 if (user->IsInvited(Ptr->name))
1566 /* user was invited to channel */
1567 /* there may be an optional channel NOTICE here */
1571 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1575 log(DEBUG,"add_channel: channel is not +i");
1578 FOREACH_RESULT(OnCheckLimit(user, Ptr));
1579 if (MOD_RESULT == 0)
1583 if (usercount(Ptr) >= Ptr->limit)
1585 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1590 log(DEBUG,"add_channel: about to walk banlist");
1592 FOREACH_RESULT(OnCheckBan(user, Ptr));
1593 if (MOD_RESULT == 0)
1595 /* check user against the channel banlist */
1598 if (Ptr->bans.size())
1600 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1602 if (match(user->GetFullHost(),i->data))
1604 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1610 log(DEBUG,"add_channel: bans checked");
1616 if ((Ptr) && (user))
1618 user->RemoveInvite(Ptr->name);
1621 log(DEBUG,"add_channel: invites removed");
1626 log(DEBUG,"Overridden checks");
1634 log(DEBUG,"Passed channel checks");
1636 for (int i =0; i != MAXCHANS; i++)
1638 log(DEBUG,"Check location %d",i);
1639 if (user->chans[i].channel == NULL)
1641 log(DEBUG,"Adding into their channel list at location %d",i);
1645 /* first user in is given ops */
1646 user->chans[i].uc_modes = UCMODE_OP;
1650 user->chans[i].uc_modes = 0;
1652 user->chans[i].channel = Ptr;
1653 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1655 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1657 // use the stamdard J token with no privilages.
1658 char buffer[MAXBUF];
1661 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1665 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1667 NetSendToAll(buffer);
1670 log(DEBUG,"Sent JOIN to client");
1674 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1675 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1678 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1679 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1680 //WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1681 FOREACH_MOD OnUserJoin(user,Ptr);
1685 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1686 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1690 /* remove a channel from a users record, and remove the record from memory
1691 * if the channel has become empty */
1693 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1695 if ((!user) || (!cname))
1697 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1704 if ((!cname) || (!user))
1709 Ptr = FindChan(cname);
1716 FOREACH_MOD OnUserPart(user,Ptr);
1717 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1719 for (int i =0; i != MAXCHANS; i++)
1721 /* zap it from the channel list of the user */
1722 if (user->chans[i].channel == Ptr)
1726 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1730 char buffer[MAXBUF];
1731 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1732 NetSendToAll(buffer);
1741 char buffer[MAXBUF];
1742 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1743 NetSendToAll(buffer);
1746 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1748 user->chans[i].uc_modes = 0;
1749 user->chans[i].channel = NULL;
1750 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1755 /* if there are no users left on the channel */
1756 if (!usercount(Ptr))
1758 chan_hash::iterator iter = chanlist.find(Ptr->name);
1760 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1762 /* kill the record */
1763 if (iter != chanlist.end())
1765 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1766 if (iter->second) delete iter->second;
1767 chanlist.erase(iter);
1773 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1775 if ((!src) || (!user) || (!Ptr) || (!reason))
1777 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1784 if ((!Ptr) || (!user) || (!src))
1789 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1791 if (!has_channel(user,Ptr))
1793 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1798 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1799 if (MOD_RESULT == ACR_DENY)
1802 if (MOD_RESULT == ACR_DEFAULT)
1804 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1806 if (cstatus(src,Ptr) == STATUS_HOP)
1808 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1812 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1820 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
1824 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
1826 for (int i =0; i != MAXCHANS; i++)
1828 /* zap it from the channel list of the user */
1829 if (user->chans[i].channel)
1830 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1832 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1833 user->chans[i].uc_modes = 0;
1834 user->chans[i].channel = NULL;
1835 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1840 /* if there are no users left on the channel */
1841 if (!usercount(Ptr))
1843 chan_hash::iterator iter = chanlist.find(Ptr->name);
1845 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1847 /* kill the record */
1848 if (iter != chanlist.end())
1850 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1851 if (iter->second) delete iter->second;
1852 chanlist.erase(iter);
1860 /* This function pokes and hacks at a parameter list like the following:
1862 * PART #winbot,#darkgalaxy :m00!
1864 * to turn it into a series of individual calls like this:
1866 * PART #winbot :m00!
1867 * PART #darkgalaxy :m00!
1869 * The seperate calls are sent to a callback function provided by the caller
1870 * (the caller will usually call itself recursively). The callback function
1871 * must be a command handler. Calling this function on a line with no list causes
1872 * no action to be taken. You must provide a starting and ending parameter number
1873 * where the range of the list can be found, useful if you have a terminating
1874 * parameter as above which is actually not part of the list, or parameters
1875 * before the actual list as well. This code is used by many functions which
1876 * can function as "one to list" (see the RFC) */
1878 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1883 char blog[32][MAXBUF];
1884 char blog2[32][MAXBUF];
1885 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1886 char keystr[MAXBUF];
1889 for (int i = 0; i <32; i++)
1892 for (int i = 0; i <32; i++)
1893 strcpy(blog2[i],"");
1896 for (int i = 0; i <10; i++)
1900 parameters[i] = moo;
1905 if (pcnt > 1) /* we have a key to copy */
1907 strlcpy(keystr,parameters[1],MAXBUF);
1911 if (!parameters[start])
1915 if (!strchr(parameters[start],','))
1920 for (int i = start; i <= end; i++)
1924 strlcat(plist,parameters[i],MAXBUF);
1932 for (int i = 0; i < t; i++)
1934 if (plist[i] == ',')
1937 strlcpy(blog[j++],param,MAXBUF);
1941 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1946 strlcpy(blog[j++],param,MAXBUF);
1949 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1954 if ((joins) && (keystr))
1956 if (strchr(keystr,','))
1960 t2 = strlen(keystr);
1961 for (int i = 0; i < t2; i++)
1963 if (keystr[i] == ',')
1966 strlcpy(blog2[j++],param,MAXBUF);
1970 strlcpy(blog2[j++],param,MAXBUF);
1975 for (j = 0; j < total; j++)
1981 for (q = end; q < pcnt-1; q++)
1983 if (parameters[q+1])
1985 pars[q-end+1] = parameters[q+1];
1988 if ((joins) && (parameters[1]))
1999 /* repeatedly call the function with the hacked parameter list */
2000 if ((joins) && (pcnt > 1))
2004 // pars[1] already set up and containing key from blog2[j]
2009 pars[1] = parameters[1];
2015 fn(pars,pcnt-(end-start),u);
2024 void kill_link(userrec *user,const char* r)
2026 user_hash::iterator iter = clientlist.find(user->nick);
2028 char reason[MAXBUF];
2030 strncpy(reason,r,MAXBUF);
2032 if (strlen(reason)>MAXQUIT)
2034 reason[MAXQUIT-1] = '\0';
2037 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2038 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2039 log(DEBUG,"closing fd %d",user->fd);
2041 /* bugfix, cant close() a nonblocking socket (sux!) */
2042 if (user->registered == 7) {
2043 FOREACH_MOD OnUserQuit(user);
2044 WriteCommonExcept(user,"QUIT :%s",reason);
2046 // Q token must go to ALL servers!!!
2047 char buffer[MAXBUF];
2048 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2049 NetSendToAll(buffer);
2052 /* push the socket on a stack of sockets due to be closed at the next opportunity
2053 * 'Client exited' is an exception to this as it means the client side has already
2054 * closed the socket, we don't need to do it.
2056 fd_reap.push_back(user->fd);
2058 bool do_purge = false;
2060 if (user->registered == 7) {
2061 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2065 if (iter != clientlist.end())
2067 log(DEBUG,"deleting user hash value %d",iter->second);
2068 if ((iter->second) && (user->registered == 7)) {
2069 if (iter->second) delete iter->second;
2071 clientlist.erase(iter);
2074 if (user->registered == 7) {
2075 purge_empty_chans();
2080 void kill_link_silent(userrec *user,const char* r)
2082 user_hash::iterator iter = clientlist.find(user->nick);
2084 char reason[MAXBUF];
2086 strncpy(reason,r,MAXBUF);
2088 if (strlen(reason)>MAXQUIT)
2090 reason[MAXQUIT-1] = '\0';
2093 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2094 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2095 log(DEBUG,"closing fd %d",user->fd);
2097 /* bugfix, cant close() a nonblocking socket (sux!) */
2098 if (user->registered == 7) {
2099 FOREACH_MOD OnUserQuit(user);
2100 WriteCommonExcept(user,"QUIT :%s",reason);
2102 // Q token must go to ALL servers!!!
2103 char buffer[MAXBUF];
2104 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2105 NetSendToAll(buffer);
2108 /* push the socket on a stack of sockets due to be closed at the next opportunity
2109 * 'Client exited' is an exception to this as it means the client side has already
2110 * closed the socket, we don't need to do it.
2112 fd_reap.push_back(user->fd);
2114 bool do_purge = false;
2116 if (iter != clientlist.end())
2118 log(DEBUG,"deleting user hash value %d",iter->second);
2119 if ((iter->second) && (user->registered == 7)) {
2120 if (iter->second) delete iter->second;
2122 clientlist.erase(iter);
2125 if (user->registered == 7) {
2126 purge_empty_chans();
2132 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2134 char* Passwd(userrec *user)
2136 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2138 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2146 bool IsDenied(userrec *user)
2148 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2150 if (match(user->host,i->host) && (i->type == CC_DENY))
2161 /* sends out an error notice to all connected clients (not to be used
2164 void send_error(char *s)
2166 log(DEBUG,"send_error: %s",s);
2167 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2169 if (isnick(i->second->nick))
2171 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2175 // fix - unregistered connections receive ERROR, not NOTICE
2176 Write(i->second->fd,"ERROR :%s",s);
2181 void Error(int status)
2183 signal (SIGALRM, SIG_IGN);
2184 signal (SIGPIPE, SIG_IGN);
2185 signal (SIGTERM, SIG_IGN);
2186 signal (SIGABRT, SIG_IGN);
2187 signal (SIGSEGV, SIG_IGN);
2188 signal (SIGURG, SIG_IGN);
2189 signal (SIGKILL, SIG_IGN);
2190 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
2191 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2196 int main(int argc, char **argv)
2200 log(DEBUG,"*** InspIRCd starting up!");
2201 if (!FileExists(CONFIG_FILE))
2203 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2204 log(DEFAULT,"main: no config");
2205 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2209 for (int i = 1; i < argc; i++)
2211 if (!strcmp(argv[i],"-nofork")) {
2214 if (!strcmp(argv[i],"-wait")) {
2217 if (!strcmp(argv[i],"-nolimit")) {
2222 strlcpy(MyExecutable,argv[0],MAXBUF);
2224 if (InspIRCd() == ERROR)
2226 log(DEFAULT,"main: daemon function bailed");
2227 printf("ERROR: could not initialise. Shutting down.\n");
2234 template<typename T> inline string ConvToStr(const T &in)
2237 if (!(tmp << in)) return string();
2241 /* re-allocates a nick in the user_hash after they change nicknames,
2242 * returns a pointer to the new user as it may have moved */
2244 userrec* ReHashNick(char* Old, char* New)
2246 user_hash::iterator newnick;
2247 user_hash::iterator oldnick = clientlist.find(Old);
2249 log(DEBUG,"ReHashNick: %s %s",Old,New);
2251 if (!strcasecmp(Old,New))
2253 log(DEBUG,"old nick is new nick, skipping");
2254 return oldnick->second;
2257 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2259 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2261 clientlist[New] = new userrec();
2262 clientlist[New] = oldnick->second;
2263 clientlist.erase(oldnick);
2265 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2267 return clientlist[New];
2270 /* adds or updates an entry in the whowas list */
2271 void AddWhoWas(userrec* u)
2273 user_hash::iterator iter = whowas.find(u->nick);
2274 userrec *a = new userrec();
2275 strlcpy(a->nick,u->nick,NICKMAX);
2276 strlcpy(a->ident,u->ident,64);
2277 strlcpy(a->dhost,u->dhost,256);
2278 strlcpy(a->host,u->host,256);
2279 strlcpy(a->fullname,u->fullname,128);
2280 strlcpy(a->server,u->server,256);
2281 a->signon = u->signon;
2283 /* MAX_WHOWAS: max number of /WHOWAS items
2284 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2285 * can be replaced by a newer one
2288 if (iter == whowas.end())
2290 if (whowas.size() == WHOWAS_MAX)
2292 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2294 // 3600 seconds in an hour ;)
2295 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
2297 if (i->second) delete i->second;
2299 log(DEBUG,"added WHOWAS entry, purged an old record");
2306 log(DEBUG,"added fresh WHOWAS entry");
2307 whowas[a->nick] = a;
2312 log(DEBUG,"updated WHOWAS entry");
2313 if (iter->second) delete iter->second;
2319 /* add a client connection to the sockets list */
2320 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2324 char resolved[MAXBUF];
2327 user_hash::iterator iter;
2329 tempnick = ConvToStr(socket) + "-unknown";
2330 sprintf(tn2,"%d-unknown",socket);
2332 iter = clientlist.find(tempnick);
2334 if (iter != clientlist.end()) return;
2337 * It is OK to access the value here this way since we know
2338 * it exists, we just created it above.
2340 * At NO other time should you access a value in a map or a
2341 * hash_map this way.
2343 clientlist[tempnick] = new userrec();
2345 NonBlocking(socket);
2346 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2348 clientlist[tempnick]->fd = socket;
2349 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2350 strncpy(clientlist[tempnick]->host, host,160);
2351 strncpy(clientlist[tempnick]->dhost, host,160);
2352 strncpy(clientlist[tempnick]->server, ServerName,256);
2353 strncpy(clientlist[tempnick]->ident, "unknown",12);
2354 clientlist[tempnick]->registered = 0;
2355 clientlist[tempnick]->signon = TIME+dns_timeout;
2356 clientlist[tempnick]->lastping = 1;
2357 clientlist[tempnick]->port = port;
2358 strncpy(clientlist[tempnick]->ip,ip,32);
2360 // set the registration timeout for this user
2361 unsigned long class_regtimeout = 90;
2362 int class_flood = 0;
2364 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2366 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2368 class_regtimeout = (unsigned long)i->registration_timeout;
2369 class_flood = i->flood;
2370 clientlist[tempnick]->pingmax = i->pingtime;
2375 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
2376 clientlist[tempnick]->timeout = TIME+class_regtimeout;
2377 clientlist[tempnick]->flood = class_flood;
2379 for (int i = 0; i < MAXCHANS; i++)
2381 clientlist[tempnick]->chans[i].channel = NULL;
2382 clientlist[tempnick]->chans[i].uc_modes = 0;
2385 if (clientlist.size() == MAXCLIENTS)
2386 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2389 char* e = matches_exception(ip);
2392 char* r = matches_zline(ip);
2395 char reason[MAXBUF];
2396 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2397 kill_link(clientlist[tempnick],reason);
2402 // this function counts all users connected, wether they are registered or NOT.
2405 return clientlist.size();
2408 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
2409 int registered_usercount(void)
2412 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2414 if ((i->second->fd) && (isnick(i->second->nick))) c++;
2419 int usercount_invisible(void)
2423 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2425 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2430 int usercount_opers(void)
2434 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2436 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2441 int usercount_unknown(void)
2445 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2447 if ((i->second->fd) && (i->second->registered != 7))
2453 long chancount(void)
2455 return chanlist.size();
2458 long count_servs(void)
2461 for (int i = 0; i < 32; i++)
2465 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2467 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2477 long servercount(void)
2479 return count_servs()+1;
2485 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2487 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2493 void ShowMOTD(userrec *user)
2495 std::string WholeMOTD = "";
2498 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2501 WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2502 for (int i = 0; i != MOTD.size(); i++)
2504 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2506 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2507 // only one write operation
2508 send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
2512 void ShowRULES(userrec *user)
2516 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2519 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2520 for (int i = 0; i != RULES.size(); i++)
2522 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2524 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2527 /* shows the message of the day, and any other on-logon stuff */
2528 void FullConnectUser(userrec* user)
2530 user->registered = 7;
2531 user->idle_lastmsg = TIME;
2532 log(DEBUG,"ConnectUser: %s",user->nick);
2534 if (strcmp(Passwd(user),"") && (!user->haspassed))
2536 kill_link(user,"Invalid password");
2541 kill_link(user,"Unauthorised connection");
2545 char match_against[MAXBUF];
2546 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2547 char* e = matches_exception(match_against);
2550 char* r = matches_gline(match_against);
2553 char reason[MAXBUF];
2554 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2555 kill_link_silent(user,reason);
2558 r = matches_kline(user->host);
2561 char reason[MAXBUF];
2562 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2563 kill_link_silent(user,reason);
2568 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2569 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2570 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2571 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2572 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2573 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2574 std::stringstream v;
2575 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2576 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2577 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2578 v << std::string(Network);
2579 std::string data005 = v.str();
2580 FOREACH_MOD On005Numeric(data005);
2581 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2582 // so i'd better split it :)
2583 std::stringstream out(data005);
2584 std::string token = "";
2585 std::string line5 = "";
2586 int token_counter = 0;
2590 line5 = line5 + token + " ";
2592 if ((token_counter >= 13) || (out.eof() == true))
2594 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2600 FOREACH_MOD OnUserConnect(user);
2601 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2603 char buffer[MAXBUF];
2604 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);
2605 NetSendToAll(buffer);
2609 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
2610 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
2611 // registration timeout maximum seconds)
2612 bool AllModulesReportReady(userrec* user)
2614 for (int i = 0; i <= MODCOUNT; i++)
2616 int res = modules[i]->OnCheckReady(user);
2623 /* shows the message of the day, and any other on-logon stuff */
2624 void ConnectUser(userrec *user)
2626 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2627 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
2629 FullConnectUser(user);
2633 void handle_version(char **parameters, int pcnt, userrec *user)
2635 char Revision[] = "$Revision$";
2637 char *s1 = Revision;
2639 char *v1 = strtok_r(s1," ",&savept);
2641 char *v2 = strtok_r(s1," ",&savept);
2644 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2648 // calls a handler function for a command
2650 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2652 for (int i = 0; i < cmdlist.size(); i++)
2654 if (!strcasecmp(cmdlist[i].command,commandname))
2656 if (cmdlist[i].handler_function)
2658 if (pcnt>=cmdlist[i].min_params)
2660 if (strchr(user->modes,cmdlist[i].flags_needed))
2662 cmdlist[i].handler_function(parameters,pcnt,user);
2670 void DoSplitEveryone()
2672 bool go_again = true;
2676 for (int i = 0; i < 32; i++)
2680 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2682 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2685 j->CloseConnection();
2686 me[i]->connectors.erase(j);
2694 log(DEBUG,"Removed server. Will remove clients...");
2695 // iterate through the userlist and remove all users on this server.
2696 // because we're dealing with a mesh, we dont have to deal with anything
2697 // "down-route" from this server (nice huh)
2699 char reason[MAXBUF];
2703 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2705 if (strcasecmp(u->second->server,ServerName))
2707 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2708 kill_link(u->second,reason);
2718 char islast(const char* s)
2721 for (int j = 0; j < 32; j++)
2725 for (int k = 0; k < me[j]->connectors.size(); k++)
2727 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2731 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2741 long map_count(const char* s)
2744 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2746 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2752 void force_nickchange(userrec* user,const char* newnick)
2759 FOREACH_RESULT(OnUserPreNick(user,newnick));
2761 kill_link(user,"Nickname collision");
2764 if (matches_qline(newnick))
2766 kill_link(user,"Nickname collision");
2774 strncpy(nick,newnick,MAXBUF);
2776 if (user->registered == 7)
2780 handle_nick(pars,1,user);
2786 int process_parameters(char **command_p,char *parameters)
2791 q = strlen(parameters);
2794 /* no parameters, command_p invalid! */
2797 if (parameters[0] == ':')
2799 command_p[0] = parameters+1;
2804 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2806 /* only one parameter */
2807 command_p[0] = parameters;
2808 if (parameters[0] == ':')
2810 if (strchr(parameters,' ') != NULL)
2818 command_p[j++] = parameters;
2819 for (int i = 0; i <= q; i++)
2821 if (parameters[i] == ' ')
2823 command_p[j++] = parameters+i+1;
2824 parameters[i] = '\0';
2825 if (command_p[j-1][0] == ':')
2827 *command_p[j-1]++; /* remove dodgy ":" */
2829 /* parameter like this marks end of the sequence */
2833 return j; /* returns total number of items in the list */
2836 void process_command(userrec *user, char* cmd)
2840 char *command_p[127];
2841 char p[MAXBUF], temp[MAXBUF];
2842 int i, j, items, cmd_found;
2844 for (int i = 0; i < 127; i++)
2845 command_p[i] = NULL;
2855 if (!strcmp(cmd,""))
2860 int total_params = 0;
2863 for (int q = 0; q < strlen(cmd)-1; q++)
2865 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2868 // found a 'trailing', we dont count them after this.
2876 // another phidjit bug...
2877 if (total_params > 126)
2879 *(strchr(cmd,' ')) = '\0';
2880 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
2884 strlcpy(temp,cmd,MAXBUF);
2886 std::string tmp = cmd;
2887 for (int i = 0; i <= MODCOUNT; i++)
2889 std::string oldtmp = tmp;
2890 modules[i]->OnServerRaw(tmp,true,user);
2893 log(DEBUG,"A Module changed the input string!");
2894 log(DEBUG,"New string: %s",tmp.c_str());
2895 log(DEBUG,"Old string: %s",oldtmp.c_str());
2899 strlcpy(cmd,tmp.c_str(),MAXBUF);
2900 strlcpy(temp,cmd,MAXBUF);
2902 if (!strchr(cmd,' '))
2904 /* no parameters, lets skip the formalities and not chop up
2906 log(DEBUG,"About to preprocess command with no params");
2908 command_p[0] = NULL;
2910 for (int i = 0; i <= strlen(cmd); i++)
2912 cmd[i] = toupper(cmd[i]);
2914 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2921 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2922 for (int i = 0; i < strlen(temp); i++)
2924 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2930 /* split the full string into a command plus parameters */
2934 if (strchr(cmd,' '))
2936 for (int i = 0; i <= strlen(cmd); i++)
2938 /* capitalise the command ONLY, leave params intact */
2939 cmd[i] = toupper(cmd[i]);
2940 /* are we nearly there yet?! :P */
2944 parameters = cmd+i+1;
2952 for (int i = 0; i <= strlen(cmd); i++)
2954 cmd[i] = toupper(cmd[i]);
2961 if (strlen(command)>MAXCOMMAND)
2963 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
2967 for (int x = 0; x < strlen(command); x++)
2969 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2971 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2973 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2975 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2982 for (int i = 0; i != cmdlist.size(); i++)
2984 if (strcmp(cmdlist[i].command,""))
2986 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2988 log(DEBUG,"Found matching command");
2992 if (strcmp(parameters,""))
2994 items = process_parameters(command_p,parameters);
2999 command_p[0] = NULL;
3005 command_p[0] = NULL;
3010 log(DEBUG,"Processing command");
3012 /* activity resets the ping pending timer */
3013 user->nping = TIME + user->pingmax;
3014 if ((items) < cmdlist[i].min_params)
3016 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
3017 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
3020 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
3022 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3023 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
3027 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
3029 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3030 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
3034 /* if the command isnt USER, PASS, or NICK, and nick is empty,
3036 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
3038 if ((!isnick(user->nick)) || (user->registered != 7))
3040 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3041 WriteServ(user->fd,"451 %s :You have not registered",command);
3045 if ((user->registered == 7) && (!strchr(user->modes,'o')))
3049 mycmd = strtok_r(DisabledCommands," ",&savept2);
3052 if (!strcasecmp(mycmd,command))
3054 // command is disabled!
3055 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
3058 mycmd = strtok_r(NULL," ",&savept2);
3063 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
3065 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
3066 if (cmdlist[i].handler_function)
3069 /* ikky /stats counters */
3074 user->bytes_in += strlen(temp);
3076 user->bytes_out+=strlen(temp);
3079 cmdlist[i].use_count++;
3080 cmdlist[i].total_bytes+=strlen(temp);
3084 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
3085 if (MOD_RESULT == 1) {
3089 /* WARNING: nothing may come after the
3090 * command handler call, as the handler
3091 * may free the user structure! */
3093 cmdlist[i].handler_function(command_p,items,user);
3099 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3100 WriteServ(user->fd,"451 %s :You have not registered",command);
3108 if ((!cmd_found) && (user))
3110 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
3111 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3116 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
3119 /* create the command and push it onto the table */
3120 strlcpy(comm.command,cmd,MAXBUF);
3121 strlcpy(comm.source,source,MAXBUF);
3122 comm.handler_function = f;
3123 comm.flags_needed = flags;
3124 comm.min_params = minparams;
3126 comm.total_bytes = 0;
3127 cmdlist.push_back(comm);
3128 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
3131 bool removecommands(const char* source)
3133 bool go_again = true;
3137 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
3139 if (!strcmp(i->source,source))
3141 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
3151 void SetupCommandTable(void)
3153 createcommand("USER",handle_user,0,4,"<core>");
3154 createcommand("NICK",handle_nick,0,1,"<core>");
3155 createcommand("QUIT",handle_quit,0,0,"<core>");
3156 createcommand("VERSION",handle_version,0,0,"<core>");
3157 createcommand("PING",handle_ping,0,1,"<core>");
3158 createcommand("PONG",handle_pong,0,1,"<core>");
3159 createcommand("ADMIN",handle_admin,0,0,"<core>");
3160 createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
3161 createcommand("INFO",handle_info,0,0,"<core>");
3162 createcommand("TIME",handle_time,0,0,"<core>");
3163 createcommand("WHOIS",handle_whois,0,1,"<core>");
3164 createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
3165 createcommand("NOTICE",handle_notice,0,2,"<core>");
3166 createcommand("JOIN",handle_join,0,1,"<core>");
3167 createcommand("NAMES",handle_names,0,0,"<core>");
3168 createcommand("PART",handle_part,0,1,"<core>");
3169 createcommand("KICK",handle_kick,0,2,"<core>");
3170 createcommand("MODE",handle_mode,0,1,"<core>");
3171 createcommand("TOPIC",handle_topic,0,1,"<core>");
3172 createcommand("WHO",handle_who,0,1,"<core>");
3173 createcommand("MOTD",handle_motd,0,0,"<core>");
3174 createcommand("RULES",handle_rules,0,0,"<core>");
3175 createcommand("OPER",handle_oper,0,2,"<core>");
3176 createcommand("LIST",handle_list,0,0,"<core>");
3177 createcommand("DIE",handle_die,'o',1,"<core>");
3178 createcommand("RESTART",handle_restart,'o',1,"<core>");
3179 createcommand("KILL",handle_kill,'o',2,"<core>");
3180 createcommand("REHASH",handle_rehash,'o',0,"<core>");
3181 createcommand("LUSERS",handle_lusers,0,0,"<core>");
3182 createcommand("STATS",handle_stats,0,1,"<core>");
3183 createcommand("USERHOST",handle_userhost,0,1,"<core>");
3184 createcommand("AWAY",handle_away,0,0,"<core>");
3185 createcommand("ISON",handle_ison,0,0,"<core>");
3186 createcommand("SUMMON",handle_summon,0,0,"<core>");
3187 createcommand("USERS",handle_users,0,0,"<core>");
3188 createcommand("INVITE",handle_invite,0,2,"<core>");
3189 createcommand("PASS",handle_pass,0,1,"<core>");
3190 createcommand("TRACE",handle_trace,'o',0,"<core>");
3191 createcommand("WHOWAS",handle_whowas,0,1,"<core>");
3192 createcommand("CONNECT",handle_connect,'o',1,"<core>");
3193 createcommand("SQUIT",handle_squit,'o',0,"<core>");
3194 createcommand("MODULES",handle_modules,0,0,"<core>");
3195 createcommand("LINKS",handle_links,0,0,"<core>");
3196 createcommand("MAP",handle_map,0,0,"<core>");
3197 createcommand("KLINE",handle_kline,'o',1,"<core>");
3198 createcommand("GLINE",handle_gline,'o',1,"<core>");
3199 createcommand("ZLINE",handle_zline,'o',1,"<core>");
3200 createcommand("QLINE",handle_qline,'o',1,"<core>");
3201 createcommand("ELINE",handle_eline,'o',1,"<core>");
3202 createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
3203 createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
3204 createcommand("SERVER",handle_server,0,0,"<core>");
3207 void process_buffer(const char* cmdbuf,userrec *user)
3211 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3218 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3221 if (!strcmp(cmdbuf,""))
3225 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3227 strlcpy(cmd,cmdbuf,MAXBUF);
3228 if (!strcmp(cmd,""))
3232 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3234 cmd[strlen(cmd)-1] = '\0';
3236 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3238 cmd[strlen(cmd)-1] = '\0';
3241 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3243 cmd[strlen(cmd)-1] = '\0';
3246 if (!strcmp(cmd,""))
3250 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3252 if ((user) && (cmd))
3254 process_command(user,cmd);
3258 void DoSync(serverrec* serv, char* tcp_host)
3261 log(DEBUG,"Sending sync");
3262 // send start of sync marker: Y <timestamp>
3263 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3264 // except the ones its receiving it from.
3265 snprintf(data,MAXBUF,"Y %d",TIME);
3266 serv->SendPacket(data,tcp_host);
3267 // send users and channels
3268 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3270 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);
3271 serv->SendPacket(data,tcp_host);
3272 if (strchr(u->second->modes,'o'))
3274 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3275 serv->SendPacket(data,tcp_host);
3277 for (int i = 0; i <= MODCOUNT; i++)
3279 string_list l = modules[i]->OnUserSync(u->second);
3280 for (int j = 0; j < l.size(); j++)
3282 strlcpy(data,l[j].c_str(),MAXBUF);
3283 serv->SendPacket(data,tcp_host);
3286 if (strcmp(chlist(u->second),""))
3288 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3289 serv->SendPacket(data,tcp_host);
3292 // send channel modes, topics etc...
3293 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3295 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3296 serv->SendPacket(data,tcp_host);
3297 for (int i = 0; i <= MODCOUNT; i++)
3299 string_list l = modules[i]->OnChannelSync(c->second);
3300 for (int j = 0; j < l.size(); j++)
3302 strlcpy(data,l[j].c_str(),MAXBUF);
3303 serv->SendPacket(data,tcp_host);
3306 if (strcmp(c->second->topic,""))
3308 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3309 serv->SendPacket(data,tcp_host);
3311 // send current banlist
3313 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3315 snprintf(data,MAXBUF,"M %s +b %s",c->second->name,b->data);
3316 serv->SendPacket(data,tcp_host);
3319 // sync global zlines, glines, etc
3320 sync_xlines(serv,tcp_host);
3322 for (int j = 0; j < 32; j++)
3326 for (int k = 0; k < me[j]->connectors.size(); k++)
3328 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3330 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3331 serv->SendPacket(data,tcp_host);
3332 NetSendMyRoutingTable();
3338 snprintf(data,MAXBUF,"F %d",TIME);
3339 serv->SendPacket(data,tcp_host);
3340 log(DEBUG,"Sent sync");
3341 // ircd sends its serverlist after the end of sync here
3345 void NetSendMyRoutingTable()
3347 // send out a line saying what is reachable to us.
3348 // E.g. if A is linked to B C and D, send out:
3350 // if its only linked to B and D send out:
3352 // if it has no links, dont even send out the line at all.
3353 char buffer[MAXBUF];
3354 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3355 bool sendit = false;
3356 for (int i = 0; i < 32; i++)
3360 for (int j = 0; j < me[i]->connectors.size(); j++)
3362 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3364 strlcat(buffer," ",MAXBUF);
3365 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3372 NetSendToAll(buffer);
3376 void DoSplit(const char* params)
3378 bool go_again = true;
3382 for (int i = 0; i < 32; i++)
3386 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3388 if (!strcasecmp(j->GetServerName().c_str(),params))
3391 j->CloseConnection();
3392 me[i]->connectors.erase(j);
3400 log(DEBUG,"Removed server. Will remove clients...");
3401 // iterate through the userlist and remove all users on this server.
3402 // because we're dealing with a mesh, we dont have to deal with anything
3403 // "down-route" from this server (nice huh)
3405 char reason[MAXBUF];
3406 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3410 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3412 if (!strcasecmp(u->second->server,params))
3414 kill_link(u->second,reason);
3422 // removes a server. Will NOT remove its users!
3424 void RemoveServer(const char* name)
3426 bool go_again = true;
3430 for (int i = 0; i < 32; i++)
3434 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3436 if (!strcasecmp(j->GetServerName().c_str(),name))
3439 j->CloseConnection();
3440 me[i]->connectors.erase(j);
3451 int reap_counter = 0;
3452 char MODERR[MAXBUF];
3459 void erase_factory(int j)
3462 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
3467 factory.push_back(NULL);
3474 void erase_module(int j)
3477 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
3483 modules.push_back(NULL);
3489 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
3493 module_names.erase(v);
3501 bool UnloadModule(const char* filename)
3503 for (int j = 0; j != module_names.size(); j++)
3505 if (module_names[j] == std::string(filename))
3507 if (modules[j]->GetVersion().Flags & VF_STATIC)
3509 log(DEFAULT,"Failed to unload STATIC module %s",filename);
3510 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
3514 log(DEBUG,"Deleting module...");
3516 log(DEBUG,"Erasing module entry...");
3518 log(DEBUG,"Removing dependent commands...");
3519 removecommands(filename);
3520 log(DEFAULT,"Module %s unloaded",filename);
3525 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
3526 snprintf(MODERR,MAXBUF,"Module not loaded");
3530 bool DirValid(char* dirandfile)
3533 strlcpy(work,dirandfile,MAXBUF);
3534 int p = strlen(work);
3535 // we just want the dir
3536 while (strlen(work))
3545 log(DEBUG,"Dir valid: %s",work);
3546 char buffer[MAXBUF], otherdir[MAXBUF];
3547 // Get the current working directory
3548 if( getcwd( buffer, MAXBUF ) == NULL )
3551 if( getcwd( otherdir, MAXBUF ) == NULL )
3554 log(DEBUG,"Dir is really: %s",otherdir);
3555 if (strlen(otherdir) >= strlen(work))
3557 otherdir[strlen(work)] = '\0';
3558 log(DEBUG,"Compare: '%s' -> '%s'",otherdir,work);
3559 if (!strcmp(otherdir,work))
3561 log(DEBUG,"Match ok");
3564 log(DEBUG,"No match");
3570 bool LoadModule(const char* filename)
3572 char modfile[MAXBUF];
3573 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
3574 if (!DirValid(modfile))
3576 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
3577 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
3580 log(DEBUG,"Loading module: %s",modfile);
3581 if (FileExists(modfile))
3583 for (int j = 0; j < module_names.size(); j++)
3585 if (module_names[j] == std::string(filename))
3587 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
3588 snprintf(MODERR,MAXBUF,"Module already loaded");
3592 ircd_module* a = new ircd_module(modfile);
3593 factory[MODCOUNT+1] = a;
3594 if (factory[MODCOUNT+1]->LastError())
3596 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
3597 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
3601 if (factory[MODCOUNT+1]->factory)
3603 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
3604 modules[MODCOUNT+1] = m;
3605 /* save the module and the module's classfactory, if
3606 * this isnt done, random crashes can occur :/ */
3607 module_names.push_back(filename);
3611 log(DEFAULT,"Unable to load %s",modfile);
3612 snprintf(MODERR,MAXBUF,"Factory function failed!");
3618 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
3619 snprintf(MODERR,MAXBUF,"Module file could not be found");
3628 struct sockaddr_in client,server;
3629 char addrs[MAXBUF][255];
3630 int incomingSockfd, result = TRUE;
3633 int selectResult = 0, selectResult2 = 0;
3634 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3635 char resolvedHost[MAXBUF];
3639 log_file = fopen("ircd.log","a+");
3642 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3646 log(DEBUG,"InspIRCd: startup: begin");
3650 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3652 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
3654 SetupCommandTable();
3655 log(DEBUG,"InspIRCd: startup: default command table set up");
3657 ReadConfig(true,NULL);
3658 if (strcmp(DieValue,""))
3660 printf("WARNING: %s\n\n",DieValue);
3661 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3664 log(DEBUG,"InspIRCd: startup: read config");
3666 int count2 = 0, count3 = 0;
3668 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3670 ConfValue("bind","port",count,configToken,&config_f);
3671 ConfValue("bind","address",count,Addr,&config_f);
3672 ConfValue("bind","type",count,Type,&config_f);
3673 if (!strcmp(Type,"servers"))
3675 char Default[MAXBUF];
3676 strcpy(Default,"no");
3677 ConfValue("bind","default",count,Default,&config_f);
3678 if (strchr(Default,'y'))
3680 defaultRoute = count3;
3681 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3683 me[count3] = new serverrec(ServerName,100L,false);
3684 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3686 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3695 ports[count2] = atoi(configToken);
3696 strlcpy(addrs[count2],Addr,256);
3699 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3702 UDPportCount = count3;
3704 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3706 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3710 /* BugFix By Craig! :p */
3712 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3714 ConfValue("module","name",count2,configToken,&config_f);
3715 printf("Loading module... \033[1;37m%s\033[0;37m\n",configToken);
3716 if (!LoadModule(configToken))
3718 log(DEBUG,"Exiting due to a module loader error.");
3719 printf("There was an error loading a module: %s\n",ModuleError());
3723 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3725 printf("\nInspIRCd is now running!\n");
3727 startup_time = time(NULL);
3731 log(VERBOSE,"Not forking as -nofork was specified");
3735 if (DaemonSeed() == ERROR)
3737 log(DEFAULT,"InspIRCd: startup: can't daemonise");
3738 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3744 ConfValue("pid","file",0,PID,&config_f);
3748 /* setup select call */
3749 FD_ZERO(&selectFds);
3750 log(DEBUG,"InspIRCd: startup: zero selects");
3751 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3753 for (count = 0; count < portCount; count++)
3755 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3757 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3760 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3762 log(DEFAULT,"InspIRCd: startup: failed to bind port %d",ports[count]);
3764 else /* well we at least bound to one socket so we'll continue */
3770 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3772 /* if we didn't bind to anything then abort */
3773 if (boundPortCount == 0)
3775 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
3780 length = sizeof (client);
3781 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3785 tvs.tv_usec = 7000L;
3792 tval.tv_usec = 7000L;
3794 int total_in_this_set = 0;
3796 bool expire_run = false;
3798 /* main loop, this never returns */
3801 #ifdef _POSIX_PRIORITY_SCHEDULING
3808 // we only read time() once per iteration rather than tons of times!
3811 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3812 // them in a list, then reap the list every second or so.
3813 if (((TIME % 5) == 0) && (!expire_run))
3816 FOREACH_MOD OnBackgroundTimer(TIME);
3820 if ((TIME % 5) == 1)
3822 if (reap_counter>300)
3824 if (fd_reap.size() > 0)
3826 for( int n = 0; n < fd_reap.size(); n++)
3828 if ((fd_reap[n] > -1))
3831 shutdown (fd_reap[n],2);
3840 // fix by brain - this must be below any manipulation of the hashmap by modules
3841 user_hash::iterator count2 = clientlist.begin();
3843 FD_ZERO(&serverfds);
3845 for (int x = 0; x != UDPportCount; x++)
3848 FD_SET(me[x]->fd, &serverfds);
3851 // serverFds timevals went here
3853 tvs.tv_usec = 7000L;
3855 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3858 for (int x = 0; x != UDPportCount; x++)
3860 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3862 char remotehost[MAXBUF],resolved[MAXBUF];
3863 length = sizeof (client);
3864 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3865 if (incomingSockfd != -1)
3867 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3868 if(CleanAndResolve(resolved, remotehost) != TRUE)
3870 strlcpy(resolved,remotehost,MAXBUF);
3872 // add to this connections ircd_connector vector
3873 // *FIX* - we need the LOCAL port not the remote port in &client!
3874 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3880 for (int x = 0; x < UDPportCount; x++)
3882 std::deque<std::string> msgs;
3884 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3886 for (int ctr = 0; ctr < msgs.size(); ctr++)
3888 char udp_msg[MAXBUF];
3889 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3890 log(DEBUG,"Processing: %s",udp_msg);
3891 if (strlen(udp_msg)<1)
3893 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3896 // during a netburst, send all data to all other linked servers
3897 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3899 if (is_uline(tcp_host))
3901 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3903 NetSendToAllExcept(tcp_host,udp_msg);
3907 NetSendToAllExcept(tcp_host,udp_msg);
3909 std::string msg = udp_msg;
3910 FOREACH_MOD OnPacketReceive(msg,tcp_host);
3911 strlcpy(udp_msg,msg.c_str(),MAXBUF);
3912 handle_link_packet(udp_msg, tcp_host, me[x]);
3919 while (count2 != clientlist.end())
3922 total_in_this_set = 0;
3924 user_hash::iterator xcount = count2;
3925 user_hash::iterator endingiter = count2;
3927 if (count2 == clientlist.end()) break;
3930 if (count2->second->fd != 0)
3932 // assemble up to 64 sockets into an fd_set
3933 // to implement a pooling mechanism.
3935 // This should be up to 64x faster than the
3936 // old implementation.
3937 while (total_in_this_set < 64)
3939 if (count2 != clientlist.end())
3941 // we don't check the state of remote users.
3942 if ((count2->second->fd != -1) && (count2->second->fd != FD_MAGIC_NUMBER))
3944 FD_SET (count2->second->fd, &sfd);
3946 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3947 // their connection class.
3948 if ((TIME > count2->second->timeout) && (count2->second->registered != 7))
3950 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3951 kill_link(count2->second,"Registration timeout");
3954 if ((TIME > count2->second->signon) && (count2->second->registered == 3) && (AllModulesReportReady(count2->second)))
3956 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3957 count2->second->dns_done = true;
3958 FullConnectUser(count2->second);
3961 if ((count2->second->dns_done) && (count2->second->registered == 3) && (AllModulesReportReady(count2->second))) // both NICK and USER... and DNS
3963 log(DEBUG,"dns done, registered=3, and modules ready, OK");
3964 FullConnectUser(count2->second);
3967 if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3969 if ((!count2->second->lastping) && (count2->second->registered == 7))
3971 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3972 kill_link(count2->second,"Ping timeout");
3975 Write(count2->second->fd,"PING :%s",ServerName);
3976 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3977 count2->second->lastping = 0;
3978 count2->second->nping = TIME+count2->second->pingmax; // was hard coded to 120
3982 total_in_this_set++;
3987 endingiter = count2;
3988 count2 = xcount; // roll back to where we were
3992 // tvals defined here
3994 tval.tv_usec = 7000L;
3995 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3997 // now loop through all of the items in this pool if any are waiting
3998 //if (selectResult2 > 0)
3999 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
4002 #ifdef _POSIX_PRIORITY_SCHEDULING
4007 if ((count2a->second->fd != FD_MAGIC_NUMBER) && (count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
4009 memset(data, 0, 10240);
4010 result = read(count2a->second->fd, data, 10240);
4014 // perform a check on the raw buffer as an array (not a string!) to remove
4015 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
4016 // hopefully this should stop even more people whining about "Unknown command: *"
4017 for (int checker = 0; checker < result; checker++)
4019 if ((data[checker] == 0) || (data[checker] == 7))
4020 data[checker] = ' ';
4022 userrec* current = count2a->second;
4023 int currfd = current->fd;
4024 char* l = strtok(data,"\n");
4029 if ((floodlines > current->flood) && (current->flood != 0))
4031 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4032 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4033 kill_link(current,"Excess flood");
4036 char sanitized[NetBufferSize];
4037 memset(sanitized, 0, NetBufferSize);
4039 for (int pt = 0; pt < strlen(l); pt++)
4043 sanitized[ptt++] = l[pt];
4046 sanitized[ptt] = '\0';
4047 if (strlen(sanitized))
4051 // we're gonna re-scan to check if the nick is gone, after every
4052 // command - if it has, we're gonna bail
4053 bool find_again = false;
4054 process_buffer(sanitized,current);
4056 // look for the user's record in case it's changed
4057 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
4059 if (c2->second->fd == currfd)
4061 // found again, update pointer
4062 current == c2->second;
4071 l = strtok(NULL,"\n");
4076 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
4078 log(DEBUG,"killing: %s",count2a->second->nick);
4079 kill_link(count2a->second,strerror(errno));
4083 // result EAGAIN means nothing read
4084 if (result == EAGAIN)
4092 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
4093 kill_link(count2a->second,"Client exited");
4094 // must bail here? kill_link removes the hash, corrupting the iterator
4095 log(DEBUG,"Bailing from client exit");
4099 else if (result > 0)
4104 for (int q = 0; q < total_in_this_set; q++)
4106 // there is no iterator += operator :(
4107 //if (count2 != clientlist.end())
4114 // set up select call
4115 for (count = 0; count < boundPortCount; count++)
4117 FD_SET (openSockfd[count], &selectFds);
4121 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4123 /* select is reporting a waiting socket. Poll them all to find out which */
4124 if (selectResult > 0)
4126 char target[MAXBUF], resolved[MAXBUF];
4127 for (count = 0; count < boundPortCount; count++)
4129 if (FD_ISSET (openSockfd[count], &selectFds))
4131 length = sizeof (client);
4132 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4134 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4135 strlcpy (resolved, target, MAXBUF);
4137 if (incomingSockfd < 0)
4139 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4140 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4144 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
4145 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4155 close (incomingSockfd);