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;
103 int openSockfd[MAXSOCKS];
105 bool unlimitcore = false;
107 time_t TIME = time(NULL);
112 template<> struct hash<in_addr>
114 template<> struct nspace::hash<in_addr>
117 size_t operator()(const struct in_addr &a) const
120 memcpy(&q,&a,sizeof(size_t));
125 template<> struct hash<string>
127 template<> struct nspace::hash<string>
130 size_t operator()(const string &s) const
133 static struct hash<const char *> strhash;
134 strlcpy(a,s.c_str(),MAXBUF);
145 bool operator()(const string& s1, const string& s2) const
147 char a[MAXBUF],b[MAXBUF];
148 strlcpy(a,s1.c_str(),MAXBUF);
149 strlcpy(b,s2.c_str(),MAXBUF);
152 return (strcasecmp(a,b) == 0);
157 struct InAddr_HashComp
160 bool operator()(const in_addr &s1, const in_addr &s2) const
165 memcpy(&q,&s1,sizeof(size_t));
166 memcpy(&p,&s2,sizeof(size_t));
174 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
175 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
176 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
177 typedef std::deque<command_t> command_table;
179 // This table references users by file descriptor.
180 // its an array to make it VERY fast, as all lookups are referenced
181 // by an integer, meaning there is no need for a scan/search operation.
182 userrec* fd_ref_table[65536];
184 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
190 user_hash clientlist;
193 command_table cmdlist;
200 struct linger linger = { 0 };
201 char MyExecutable[1024];
202 int boundPortCount = 0;
203 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
204 int defaultRoute = 0;
205 char ModPath[MAXBUF];
209 int has_channel(userrec *u, chanrec *c);
210 int usercount(chanrec *c);
211 int usercount_i(chanrec *c);
212 char* Passwd(userrec *user);
213 bool IsDenied(userrec *user);
214 void AddWhoWas(userrec* u);
216 std::vector<long> auth_cookies;
217 std::stringstream config_f(stringstream::in | stringstream::out);
219 std::vector<userrec*> all_opers;
221 void AddOper(userrec* user)
223 log(DEBUG,"Oper added to optimization list");
224 all_opers.push_back(user);
227 void DeleteOper(userrec* user)
229 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
233 log(DEBUG,"Oper removed from optimization list");
242 char Revision[] = "$Revision$";
245 char *v2 = strtok_r(s1," ",&savept);
247 v2 = strtok_r(s1," ",&savept);
249 return (long)(atof(v2)*10000);
253 std::string getservername()
258 std::string getserverdesc()
263 std::string getnetworkname()
268 std::string getadminname()
273 std::string getadminemail()
278 std::string getadminnick()
283 void log(int level,char *text, ...)
285 char textbuffer[MAXBUF];
288 struct tm * timeinfo;
289 if (level < LogLevel)
293 timeinfo = localtime (&rawtime);
298 va_start (argsPtr, text);
299 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
301 strlcpy(b,asctime(timeinfo),MAXBUF);
302 b[24] = ':'; // we know this is the end of the time string
303 fprintf(log_file,"%s %s\n",b,textbuffer);
306 // nofork enabled? display it on terminal too
307 printf("%s %s\n",b,textbuffer);
312 void readfile(file_cache &F, const char* fname)
315 char linebuf[MAXBUF];
317 log(DEBUG,"readfile: loading %s",fname);
319 file = fopen(fname,"r");
324 fgets(linebuf,sizeof(linebuf),file);
325 linebuf[strlen(linebuf)-1]='\0';
332 F.push_back(linebuf);
339 log(DEBUG,"readfile: failed to load file: %s",fname);
341 log(DEBUG,"readfile: loaded %s, %lu lines",fname,(unsigned long)F.size());
344 void ReadConfig(bool bail, userrec* user)
346 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
347 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF];
349 std::stringstream errstr;
351 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
356 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
364 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
365 while (!errstr.eof())
367 errstr.getline(dataline,1024);
368 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
373 WriteOpers("There were errors in the configuration file:",user->nick);
374 while (!errstr.eof())
376 errstr.getline(dataline,1024);
377 WriteOpers(dataline);
384 ConfValue("server","name",0,ServerName,&config_f);
385 ConfValue("server","description",0,ServerDesc,&config_f);
386 ConfValue("server","network",0,Network,&config_f);
387 ConfValue("admin","name",0,AdminName,&config_f);
388 ConfValue("admin","email",0,AdminEmail,&config_f);
389 ConfValue("admin","nick",0,AdminNick,&config_f);
390 ConfValue("files","motd",0,motd,&config_f);
391 ConfValue("files","rules",0,rules,&config_f);
392 ConfValue("power","diepass",0,diepass,&config_f);
393 ConfValue("power","pause",0,pauseval,&config_f);
394 ConfValue("power","restartpass",0,restartpass,&config_f);
395 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
396 ConfValue("die","value",0,DieValue,&config_f);
397 ConfValue("options","loglevel",0,dbg,&config_f);
398 ConfValue("options","netbuffersize",0,NB,&config_f);
399 ConfValue("options","maxwho",0,MW,&config_f);
400 ConfValue("options","allowhalfop",0,AH,&config_f);
401 ConfValue("options","allowprotect",0,AP,&config_f);
402 ConfValue("options","allowfounder",0,AF,&config_f);
403 ConfValue("dns","server",0,DNSServer,&config_f);
404 ConfValue("dns","timeout",0,DNT,&config_f);
405 ConfValue("options","moduledir",0,ModPath,&config_f);
406 ConfValue("disabled","commands",0,DisabledCommands,&config_f);
408 NetBufferSize = atoi(NB);
409 MaxWhoResults = atoi(MW);
410 dns_timeout = atoi(DNT);
414 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
416 strlcpy(ModPath,MOD_PATH,MAXBUF);
417 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
418 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
419 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
420 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
422 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
423 NetBufferSize = 10240;
425 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
427 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
430 if (!strcmp(dbg,"debug"))
432 if (!strcmp(dbg,"verbose"))
434 if (!strcmp(dbg,"default"))
436 if (!strcmp(dbg,"sparse"))
438 if (!strcmp(dbg,"none"))
441 log(DEFAULT,"Reading message of the day...");
442 readfile(RULES,rules);
443 log(DEFAULT,"Reading connect classes...");
445 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
448 ConfValue("connect","allow",i,Value,&config_f);
449 ConfValue("connect","timeout",i,timeout,&config_f);
450 ConfValue("connect","flood",i,flood,&config_f);
451 ConfValue("connect","pingfreq",i,pfreq,&config_f);
452 ConfValue("connect","threshold",i,thold,&config_f);
455 strlcpy(c.host,Value,MAXBUF);
457 strlcpy(Value,"",MAXBUF);
458 ConfValue("connect","password",i,Value,&config_f);
459 strlcpy(c.pass,Value,MAXBUF);
460 c.registration_timeout = 90; // default is 2 minutes
462 c.flood = atoi(flood);
466 c.threshold = atoi(thold);
470 c.registration_timeout = atoi(timeout);
474 c.pingtime = atoi(pfreq);
476 Classes.push_back(c);
477 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%lu flood=%lu",c.host,c.pass,(unsigned long)c.registration_timeout,(unsigned long)c.flood);
481 ConfValue("connect","deny",i,Value,&config_f);
482 strlcpy(c.host,Value,MAXBUF);
484 Classes.push_back(c);
485 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
489 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
490 read_xline_defaults();
491 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
493 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
496 log(DEFAULT,"Adding and removing modules due to rehash...");
498 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
500 // store the old module names
501 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
503 old_module_names.push_back(*t);
506 // get the new module names
507 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
509 ConfValue("module","name",count2,Value,&config_f);
510 new_module_names.push_back(Value);
513 // now create a list of new modules that are due to be loaded
514 // and a seperate list of modules which are due to be unloaded
515 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
518 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
524 added_modules.push_back(*_new);
526 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
529 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
535 removed_modules.push_back(*oldm);
537 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
539 int rem = 0, add = 0;
540 if (!removed_modules.empty())
541 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
543 if (UnloadModule(removing->c_str()))
545 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
546 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
551 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
554 if (!added_modules.empty())
555 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
557 if (LoadModule(adding->c_str()))
559 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
560 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
565 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
568 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
572 /* write formatted text to a socket, in same format as printf */
574 void Write(int sock,char *text, ...)
576 if (sock == FD_MAGIC_NUMBER)
580 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
583 char textbuffer[MAXBUF];
587 va_start (argsPtr, text);
588 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
590 int bytes = snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
595 FOREACH_RESULT(OnRawSocketWrite(sock,tb,bytes > 512 ? 512 : bytes));
597 write(sock,tb,bytes > 512 ? 512 : bytes);
598 if (fd_ref_table[sock])
600 fd_ref_table[sock]->bytes_out += (bytes > 512 ? 512 : bytes);
601 fd_ref_table[sock]->cmds_out++;
603 statsSent += (bytes > 512 ? 512 : bytes);
607 /* write a server formatted numeric response to a single socket */
609 void WriteServ(int sock, char* text, ...)
611 if (sock == FD_MAGIC_NUMBER)
615 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
618 char textbuffer[MAXBUF],tb[MAXBUF];
620 va_start (argsPtr, text);
622 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
624 int bytes = snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
629 FOREACH_RESULT(OnRawSocketWrite(sock,tb,bytes > 512 ? 512 : bytes));
631 write(sock,tb,bytes > 512 ? 512 : bytes);
632 if (fd_ref_table[sock])
634 fd_ref_table[sock]->bytes_out += (bytes > 512 ? 512 : bytes);
635 fd_ref_table[sock]->cmds_out++;
637 statsSent += (bytes > 512 ? 512 : bytes);
641 /* write text from an originating user to originating user */
643 void WriteFrom(int sock, userrec *user,char* text, ...)
645 if (sock == FD_MAGIC_NUMBER)
647 if ((!text) || (!user))
649 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
652 char textbuffer[MAXBUF],tb[MAXBUF];
654 va_start (argsPtr, text);
656 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
658 int bytes = snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
663 FOREACH_RESULT(OnRawSocketWrite(sock,tb,bytes > 512 ? 512 : bytes));
665 write(sock,tb,bytes > 512 ? 512 : bytes);
666 if (fd_ref_table[sock])
668 fd_ref_table[sock]->bytes_out += (bytes > 512 ? 512 : bytes);
669 fd_ref_table[sock]->cmds_out++;
671 statsSent += (bytes > 512 ? 512 : bytes);
675 /* write text to an destination user from a source user (e.g. user privmsg) */
677 void WriteTo(userrec *source, userrec *dest,char *data, ...)
679 if ((!dest) || (!data))
681 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
684 if (dest->fd == FD_MAGIC_NUMBER)
686 char textbuffer[MAXBUF],tb[MAXBUF];
688 va_start (argsPtr, data);
689 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
693 // if no source given send it from the server.
696 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
700 WriteFrom(dest->fd,source,"%s",textbuffer);
704 /* write formatted text from a source user to all users on a channel
705 * including the sender (NOT for privmsg, notice etc!) */
707 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
709 if ((!Ptr) || (!user) || (!text))
711 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
714 char textbuffer[MAXBUF];
716 va_start (argsPtr, text);
717 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
720 std::vector<char*> *ulist = Ptr->GetUsers();
721 for (int j = 0; j < ulist->size(); j++)
723 char* o = (*ulist)[j];
724 userrec* otheruser = (userrec*)o;
725 if (otheruser->fd != FD_MAGIC_NUMBER)
726 WriteTo(user,otheruser,"%s",textbuffer);
730 /* write formatted text from a source user to all users on a channel
731 * including the sender (NOT for privmsg, notice etc!) doesnt send to
732 * users on remote servers */
734 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
736 if ((!Ptr) || (!text))
738 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
741 char textbuffer[MAXBUF];
743 va_start (argsPtr, text);
744 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
747 std::vector<char*> *ulist = Ptr->GetUsers();
748 for (int j = 0; j < ulist->size(); j++)
750 char* o = (*ulist)[j];
751 userrec* otheruser = (userrec*)o;
752 if ((otheruser->fd != FD_MAGIC_NUMBER) && (otheruser->fd != -1) && (otheruser != user))
756 WriteServ(otheruser->fd,"%s",textbuffer);
760 WriteTo(user,otheruser,"%s",textbuffer);
767 void WriteChannelWithServ(char* ServName, chanrec* Ptr, char* text, ...)
769 if ((!Ptr) || (!text))
771 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
774 char textbuffer[MAXBUF];
776 va_start (argsPtr, text);
777 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
781 std::vector<char*> *ulist = Ptr->GetUsers();
782 for (int j = 0; j < ulist->size(); j++)
784 char* o = (*ulist)[j];
785 userrec* otheruser = (userrec*)o;
786 if (otheruser->fd != FD_MAGIC_NUMBER)
787 WriteServ(otheruser->fd,"%s",textbuffer);
792 /* write formatted text from a source user to all users on a channel except
793 * for the sender (for privmsg etc) */
795 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
797 if ((!Ptr) || (!user) || (!text))
799 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
802 char textbuffer[MAXBUF];
804 va_start (argsPtr, text);
805 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
808 std::vector<char*> *ulist = Ptr->GetUsers();
809 for (int j = 0; j < ulist->size(); j++)
811 char* o = (*ulist)[j];
812 userrec* otheruser = (userrec*)o;
813 if ((otheruser->fd != FD_MAGIC_NUMBER) && (user != otheruser))
814 WriteFrom(otheruser->fd,user,"%s",textbuffer);
819 std::string GetServerDescription(char* servername)
821 for (int j = 0; j < 32; j++)
825 for (int k = 0; k < me[j]->connectors.size(); k++)
827 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
829 return me[j]->connectors[k].GetDescription();
833 return ServerDesc; // not a remote server that can be found, it must be me.
838 /* write a formatted string to all users who share at least one common
839 * channel, including the source user e.g. for use in NICK */
841 void WriteCommon(userrec *u, char* text, ...)
845 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
849 if (u->registered != 7) {
850 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
854 char textbuffer[MAXBUF];
856 va_start (argsPtr, text);
857 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
860 // FIX: Stops a message going to the same person more than once
861 std::vector<int> already_sent;
863 for (int i = 0; i < MAXCHANS; i++)
865 if (u->chans[i].channel)
867 std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
868 for (int j = 0; j < ulist->size(); j++)
870 char* o = (*ulist)[j];
871 userrec* otheruser = (userrec*)o;
873 for (int t = 0; t < already_sent.size(); t++)
875 if (already_sent[t] == otheruser->fd)
883 already_sent.push_back(otheruser->fd);
884 WriteFrom(otheruser->fd,u,"%s",textbuffer);
889 // if the user was not in any channels, no users will receive the text. Make sure the user
890 // receives their OWN message for WriteCommon
891 if (!already_sent.size())
893 WriteFrom(u->fd,u,"%s",textbuffer);
897 /* write a formatted string to all users who share at least one common
898 * channel, NOT including the source user e.g. for use in QUIT */
900 void WriteCommonExcept(userrec *u, char* text, ...)
904 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
908 if (u->registered != 7) {
909 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
913 char textbuffer[MAXBUF];
915 va_start (argsPtr, text);
916 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
919 std::vector<int> already_sent;
921 for (int i = 0; i < MAXCHANS; i++)
923 if (u->chans[i].channel)
925 std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
926 for (int j = 0; j < ulist->size(); j++)
928 char* o = (*ulist)[j];
929 userrec* otheruser = (userrec*)o;
933 for (int t = 0; t < already_sent.size(); t++)
935 if (already_sent[t] == otheruser->fd)
943 already_sent.push_back(otheruser->fd);
944 WriteFrom(otheruser->fd,u,"%s",textbuffer);
952 void WriteOpers(char* text, ...)
956 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
960 char textbuffer[MAXBUF];
962 va_start (argsPtr, text);
963 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
966 for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
969 if ((a) && (a->fd != FD_MAGIC_NUMBER))
971 if (strchr(a->modes,'s'))
973 // send server notices to all with +s
974 WriteServ(a->fd,"NOTICE %s :%s",a->nick,textbuffer);
980 void NoticeAllOpers(userrec *source, bool local_only, char* text, ...)
982 if ((!text) || (!source))
984 log(DEFAULT,"*** BUG *** NoticeAllOpers was given an invalid parameter");
988 char textbuffer[MAXBUF];
990 va_start (argsPtr, text);
991 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
994 for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
997 if ((a) && (a->fd != FD_MAGIC_NUMBER))
999 if (strchr(a->modes,'s'))
1001 // send server notices to all with +s
1002 WriteServ(a->fd,"NOTICE %s :*** Notice From %s: %s",a->nick,source->nick,textbuffer);
1009 char buffer[MAXBUF];
1010 snprintf(buffer,MAXBUF,"V %s @* :%s",source->nick,textbuffer);
1011 NetSendToAll(buffer);
1015 // returns TRUE of any users on channel C occupy server 'servername'.
1017 bool ChanAnyOnThisServer(chanrec *c,char* servername)
1019 log(DEBUG,"ChanAnyOnThisServer");
1021 std::vector<char*> *ulist = c->GetUsers();
1022 for (int j = 0; j < ulist->size(); j++)
1024 char* o = (*ulist)[j];
1025 userrec* user = (userrec*)o;
1026 if (!strcasecmp(user->server,servername))
1032 // returns true if user 'u' shares any common channels with any users on server 'servername'
1034 bool CommonOnThisServer(userrec* u,const char* servername)
1036 log(DEBUG,"ChanAnyOnThisServer");
1038 for (int i = 0; i < MAXCHANS; i++)
1040 if (u->chans[i].channel)
1042 std::vector<char*> *ulist = u->chans[i].channel->GetUsers();
1043 for (int j = 0; j < ulist->size(); j++)
1045 char* o = (*ulist)[j];
1046 userrec* user = (userrec*)o;
1047 if (!strcasecmp(user->server,servername))
1056 void NetSendToCommon(userrec* u, char* s)
1058 char buffer[MAXBUF];
1059 snprintf(buffer,MAXBUF,"%s",s);
1061 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
1063 std::string msg = buffer;
1064 FOREACH_MOD OnPacketTransmit(msg,s);
1065 strlcpy(buffer,msg.c_str(),MAXBUF);
1067 for (int j = 0; j < 32; j++)
1071 for (int k = 0; k < me[j]->connectors.size(); k++)
1073 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
1075 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1083 void NetSendToAll(char* s)
1085 char buffer[MAXBUF];
1086 snprintf(buffer,MAXBUF,"%s",s);
1088 log(DEBUG,"NetSendToAll: '%s'",s);
1090 std::string msg = buffer;
1091 FOREACH_MOD OnPacketTransmit(msg,s);
1092 strlcpy(buffer,msg.c_str(),MAXBUF);
1094 for (int j = 0; j < 32; j++)
1098 for (int k = 0; k < me[j]->connectors.size(); k++)
1100 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1106 void NetSendToAllAlive(char* s)
1108 char buffer[MAXBUF];
1109 snprintf(buffer,MAXBUF,"%s",s);
1111 log(DEBUG,"NetSendToAllAlive: '%s'",s);
1113 std::string msg = buffer;
1114 FOREACH_MOD OnPacketTransmit(msg,s);
1115 strlcpy(buffer,msg.c_str(),MAXBUF);
1117 for (int j = 0; j < 32; j++)
1121 for (int k = 0; k < me[j]->connectors.size(); k++)
1123 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
1125 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1129 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
1137 void NetSendToOne(char* target,char* s)
1139 char buffer[MAXBUF];
1140 snprintf(buffer,MAXBUF,"%s",s);
1142 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
1144 std::string msg = buffer;
1145 FOREACH_MOD OnPacketTransmit(msg,s);
1146 strlcpy(buffer,msg.c_str(),MAXBUF);
1148 for (int j = 0; j < 32; j++)
1152 for (int k = 0; k < me[j]->connectors.size(); k++)
1154 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1156 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1163 void NetSendToAllExcept(const char* target,char* s)
1165 char buffer[MAXBUF];
1166 snprintf(buffer,MAXBUF,"%s",s);
1168 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
1170 std::string msg = buffer;
1171 FOREACH_MOD OnPacketTransmit(msg,s);
1172 strlcpy(buffer,msg.c_str(),MAXBUF);
1174 for (int j = 0; j < 32; j++)
1178 for (int k = 0; k < me[j]->connectors.size(); k++)
1180 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1182 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1190 void WriteMode(const char* modes, int flags, const char* text, ...)
1192 if ((!text) || (!modes) || (!flags))
1194 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1198 char textbuffer[MAXBUF];
1200 va_start (argsPtr, text);
1201 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1203 int modelen = strlen(modes);
1205 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1207 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
1209 bool send_to_user = false;
1211 if (flags == WM_AND)
1213 send_to_user = true;
1214 for (int n = 0; n < modelen; n++)
1216 if (!hasumode(i->second,modes[n]))
1218 send_to_user = false;
1223 else if (flags == WM_OR)
1225 send_to_user = false;
1226 for (int n = 0; n < modelen; n++)
1228 if (hasumode(i->second,modes[n]))
1230 send_to_user = true;
1238 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1245 void NoticeAll(userrec *source, bool local_only, char* text, ...)
1247 if ((!text) || (!source))
1249 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
1253 char textbuffer[MAXBUF];
1255 va_start (argsPtr, text);
1256 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1259 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1261 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
1263 WriteFrom(i->second->fd,source,"NOTICE $* :%s",textbuffer);
1269 char buffer[MAXBUF];
1270 snprintf(buffer,MAXBUF,"V %s * :%s",source->nick,textbuffer);
1271 NetSendToAll(buffer);
1276 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
1278 if ((!text) || (!source))
1280 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1284 char textbuffer[MAXBUF];
1286 va_start (argsPtr, text);
1287 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1290 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1292 if ((i->second) && (i->second->fd != FD_MAGIC_NUMBER))
1294 if (strchr(i->second->modes,'w'))
1296 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1303 char buffer[MAXBUF];
1304 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1305 NetSendToAll(buffer);
1309 /* convert a string to lowercase. Note following special circumstances
1310 * taken from RFC 1459. Many "official" server branches still hold to this
1311 * rule so i will too;
1313 * Because of IRC's scandanavian origin, the characters {}| are
1314 * considered to be the lower case equivalents of the characters []\,
1315 * respectively. This is a critical issue when determining the
1316 * equivalence of two nicknames.
1319 void strlower(char *n)
1325 for (int i = 0; n[i] != 0; i++)
1327 n[i] = tolower(n[i]);
1339 /* Find a user record by nickname and return a pointer to it */
1341 userrec* Find(std::string nick)
1343 user_hash::iterator iter = clientlist.find(nick);
1345 if (iter == clientlist.end())
1346 /* Couldn't find it */
1349 return iter->second;
1352 /* find a channel record by channel name and return a pointer to it */
1354 chanrec* FindChan(const char* chan)
1358 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1362 chan_hash::iterator iter = chanlist.find(chan);
1364 if (iter == chanlist.end())
1365 /* Couldn't find it */
1368 return iter->second;
1372 long GetMaxBans(char* name)
1375 for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1377 ConfValue("banlist","chan",count,CM,&config_f);
1380 ConfValue("banlist","limit",count,CM,&config_f);
1388 void purge_empty_chans(userrec* u)
1391 int go_again = 1, purge = 0;
1393 // firstly decrement the count on each channel
1394 for (int f = 0; f < MAXCHANS; f++)
1396 if (u->chans[f].channel)
1398 u->chans[f].channel->DecUserCounter();
1399 u->chans[f].channel->DelUser((char*)u);
1403 for (int i = 0; i < MAXCHANS; i++)
1405 if (u->chans[i].channel)
1407 if (!usercount(u->chans[i].channel))
1409 chan_hash::iterator i2 = chanlist.find(u->chans[i].channel->name);
1410 /* kill the record */
1411 if (i2 != chanlist.end())
1413 log(DEBUG,"del_channel: destroyed: %s",i2->second->name);
1419 u->chans[i].channel = NULL;
1424 log(DEBUG,"skipped purge for %s",u->chans[i].channel->name);
1428 log(DEBUG,"completed channel purge, killed %lu",(unsigned long)purge);
1434 char scratch[MAXBUF];
1435 char sparam[MAXBUF];
1437 char* chanmodes(chanrec *chan)
1441 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1448 if (chan->noexternal)
1450 strlcat(scratch,"n",MAXMODES);
1452 if (chan->topiclock)
1454 strlcat(scratch,"t",MAXMODES);
1458 strlcat(scratch,"k",MAXMODES);
1462 strlcat(scratch,"l",MAXMODES);
1464 if (chan->inviteonly)
1466 strlcat(scratch,"i",MAXMODES);
1468 if (chan->moderated)
1470 strlcat(scratch,"m",MAXMODES);
1474 strlcat(scratch,"s",MAXMODES);
1476 if (chan->c_private)
1478 strlcat(scratch,"p",MAXMODES);
1482 strlcat(sparam," ",MAXBUF);
1483 strlcat(sparam,chan->key,MAXBUF);
1488 sprintf(foo," %lu",(unsigned long)chan->limit);
1489 strlcat(sparam,foo,MAXBUF);
1491 if (*chan->custom_modes)
1493 strlcat(scratch,chan->custom_modes,MAXMODES);
1494 for (int z = 0; chan->custom_modes[z] != 0; z++)
1496 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1499 strlcat(sparam," ",MAXBUF);
1500 strlcat(sparam,extparam.c_str(),MAXBUF);
1504 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1505 strlcat(scratch,sparam,MAXMODES);
1510 /* compile a userlist of a channel into a string, each nick seperated by
1511 * spaces and op, voice etc status shown as @ and + */
1513 void userlist(userrec *user,chanrec *c)
1515 if ((!c) || (!user))
1517 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1521 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1522 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1524 if (has_channel(i->second,c))
1526 if (isnick(i->second->nick))
1528 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1530 /* user is +i, and source not on the channel, does not show
1531 * nick in NAMES list */
1534 strlcat(list,cmode(i->second,c),MAXBUF);
1535 strlcat(list,i->second->nick,MAXBUF);
1536 strlcat(list," ",MAXBUF);
1537 if (strlen(list)>(480-NICKMAX))
1539 /* list overflowed into
1540 * multiple numerics */
1541 WriteServ(user->fd,"%s",list);
1542 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1547 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1549 WriteServ(user->fd,"%s",list);
1553 /* return a count of the users on a specific channel accounting for
1554 * invisible users who won't increase the count. e.g. for /LIST */
1556 int usercount_i(chanrec *c)
1562 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1567 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1571 if (has_channel(i->second,c))
1573 if (isnick(i->second->nick))
1575 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1577 /* user is +i, and source not on the channel, does not show
1578 * nick in NAMES list */
1586 log(DEBUG,"usercount_i: %s %lu",c->name,(unsigned long)count);
1591 int usercount(chanrec *c)
1595 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1598 int count = c->GetUserCounter();
1599 log(DEBUG,"usercount: %s %lu",c->name,(unsigned long)count);
1604 /* add a channel to a user, creating the record for it if needed and linking
1605 * it to the user record */
1607 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1609 if ((!user) || (!cn))
1611 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1619 strncpy(cname,cn,MAXBUF);
1621 // we MUST declare this wherever we use FOREACH_RESULT
1624 if (strlen(cname) > CHANMAX-1)
1626 cname[CHANMAX-1] = '\0';
1629 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1631 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1633 return NULL; // already on the channel!
1637 if (!FindChan(cname))
1640 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1641 if (MOD_RESULT == 1) {
1645 /* create a new one */
1646 log(DEBUG,"add_channel: creating: %s",cname);
1648 chanlist[cname] = new chanrec();
1650 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1651 chanlist[cname]->topiclock = 1;
1652 chanlist[cname]->noexternal = 1;
1653 chanlist[cname]->created = TIME;
1654 strcpy(chanlist[cname]->topic, "");
1655 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1656 chanlist[cname]->topicset = 0;
1657 Ptr = chanlist[cname];
1658 log(DEBUG,"add_channel: created: %s",cname);
1659 /* set created to 2 to indicate user
1660 * is the first in the channel
1661 * and should be given ops */
1667 /* channel exists, just fish out a pointer to its struct */
1668 Ptr = FindChan(cname);
1671 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1673 // the override flag allows us to bypass channel modes
1674 // and bans (used by servers)
1675 if ((!override) || (!strcasecmp(user->server,ServerName)))
1677 log(DEBUG,"Not overriding...");
1679 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1680 if (MOD_RESULT == 1) {
1683 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1687 log(DEBUG,"add_channel: checking key, invite, etc");
1689 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
1690 if (MOD_RESULT == 0)
1694 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1697 log(DEBUG,"add_channel: no key given in JOIN");
1698 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1703 if (strcasecmp(key,Ptr->key))
1705 log(DEBUG,"add_channel: bad key given in JOIN");
1706 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1711 log(DEBUG,"add_channel: no key");
1714 FOREACH_RESULT(OnCheckInvite(user, Ptr));
1715 if (MOD_RESULT == 0)
1717 if (Ptr->inviteonly)
1719 log(DEBUG,"add_channel: channel is +i");
1720 if (user->IsInvited(Ptr->name))
1722 /* user was invited to channel */
1723 /* there may be an optional channel NOTICE here */
1727 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1731 log(DEBUG,"add_channel: channel is not +i");
1734 FOREACH_RESULT(OnCheckLimit(user, Ptr));
1735 if (MOD_RESULT == 0)
1739 if (usercount(Ptr) >= Ptr->limit)
1741 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1746 log(DEBUG,"add_channel: about to walk banlist");
1748 FOREACH_RESULT(OnCheckBan(user, Ptr));
1749 if (MOD_RESULT == 0)
1751 /* check user against the channel banlist */
1754 if (Ptr->bans.size())
1756 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1758 if (match(user->GetFullHost(),i->data))
1760 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1766 log(DEBUG,"add_channel: bans checked");
1772 if ((Ptr) && (user))
1774 user->RemoveInvite(Ptr->name);
1777 log(DEBUG,"add_channel: invites removed");
1782 log(DEBUG,"Overridden checks");
1790 log(DEBUG,"Passed channel checks");
1792 for (int index =0; index != MAXCHANS; index++)
1794 log(DEBUG,"Check location %d",index);
1795 if (user->chans[index].channel == NULL)
1797 log(DEBUG,"Adding into their channel list at location %d",index);
1801 /* first user in is given ops */
1802 user->chans[index].uc_modes = UCMODE_OP;
1806 user->chans[index].uc_modes = 0;
1808 user->chans[index].channel = Ptr;
1809 Ptr->IncUserCounter();
1810 Ptr->AddUser((char*)user);
1811 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1813 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1815 // use the stamdard J token with no privilages.
1816 char buffer[MAXBUF];
1819 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1823 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1825 NetSendToAll(buffer);
1828 log(DEBUG,"Sent JOIN to client");
1832 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1833 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
1836 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1837 //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1838 //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
1839 FOREACH_MOD OnUserJoin(user,Ptr);
1843 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1844 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1848 /* remove a channel from a users record, and remove the record from memory
1849 * if the channel has become empty */
1851 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1853 if ((!user) || (!cname))
1855 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1861 if ((!cname) || (!user))
1866 Ptr = FindChan(cname);
1873 FOREACH_MOD OnUserPart(user,Ptr);
1874 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1876 for (int i =0; i != MAXCHANS; i++)
1878 /* zap it from the channel list of the user */
1879 if (user->chans[i].channel == Ptr)
1883 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1887 char buffer[MAXBUF];
1888 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1889 NetSendToAll(buffer);
1898 char buffer[MAXBUF];
1899 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1900 NetSendToAll(buffer);
1903 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1905 user->chans[i].uc_modes = 0;
1906 user->chans[i].channel = NULL;
1907 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1912 Ptr->DecUserCounter();
1913 Ptr->DelUser((char*)user);
1915 /* if there are no users left on the channel */
1916 if (!usercount(Ptr))
1918 chan_hash::iterator iter = chanlist.find(Ptr->name);
1920 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1922 /* kill the record */
1923 if (iter != chanlist.end())
1925 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1927 chanlist.erase(iter);
1933 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1935 if ((!src) || (!user) || (!Ptr) || (!reason))
1937 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1941 if ((!Ptr) || (!user) || (!src))
1946 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1948 if (!has_channel(user,Ptr))
1950 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1955 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1956 if (MOD_RESULT == ACR_DENY)
1959 if (MOD_RESULT == ACR_DEFAULT)
1961 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1963 if (cstatus(src,Ptr) == STATUS_HOP)
1965 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1969 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1977 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
1981 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
1983 for (int i =0; i != MAXCHANS; i++)
1985 /* zap it from the channel list of the user */
1986 if (user->chans[i].channel)
1987 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1989 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1990 user->chans[i].uc_modes = 0;
1991 user->chans[i].channel = NULL;
1992 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1997 Ptr->DecUserCounter();
1998 Ptr->DelUser((char*)user);
2000 /* if there are no users left on the channel */
2001 if (!usercount(Ptr))
2003 chan_hash::iterator iter = chanlist.find(Ptr->name);
2005 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
2007 /* kill the record */
2008 if (iter != chanlist.end())
2010 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
2012 chanlist.erase(iter);
2020 /* This function pokes and hacks at a parameter list like the following:
2022 * PART #winbot,#darkgalaxy :m00!
2024 * to turn it into a series of individual calls like this:
2026 * PART #winbot :m00!
2027 * PART #darkgalaxy :m00!
2029 * The seperate calls are sent to a callback function provided by the caller
2030 * (the caller will usually call itself recursively). The callback function
2031 * must be a command handler. Calling this function on a line with no list causes
2032 * no action to be taken. You must provide a starting and ending parameter number
2033 * where the range of the list can be found, useful if you have a terminating
2034 * parameter as above which is actually not part of the list, or parameters
2035 * before the actual list as well. This code is used by many functions which
2036 * can function as "one to list" (see the RFC) */
2038 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2043 char blog[32][MAXBUF];
2044 char blog2[32][MAXBUF];
2045 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2046 char keystr[MAXBUF];
2049 for (int i = 0; i <32; i++)
2052 for (int i = 0; i <32; i++)
2053 strcpy(blog2[i],"");
2056 for (int i = 0; i <10; i++)
2060 parameters[i] = moo;
2065 if (pcnt > 1) /* we have a key to copy */
2067 strlcpy(keystr,parameters[1],MAXBUF);
2071 if (!parameters[start])
2075 if (!strchr(parameters[start],','))
2080 for (int i = start; i <= end; i++)
2084 strlcat(plist,parameters[i],MAXBUF);
2092 for (int i = 0; i < t; i++)
2094 if (plist[i] == ',')
2097 strlcpy(blog[j++],param,MAXBUF);
2101 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
2106 strlcpy(blog[j++],param,MAXBUF);
2109 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2114 if ((joins) && (keystr))
2116 if (strchr(keystr,','))
2120 t2 = strlen(keystr);
2121 for (int i = 0; i < t2; i++)
2123 if (keystr[i] == ',')
2126 strlcpy(blog2[j++],param,MAXBUF);
2130 strlcpy(blog2[j++],param,MAXBUF);
2135 for (j = 0; j < total; j++)
2141 for (q = end; q < pcnt-1; q++)
2143 if (parameters[q+1])
2145 pars[q-end+1] = parameters[q+1];
2148 if ((joins) && (parameters[1]))
2159 /* repeatedly call the function with the hacked parameter list */
2160 if ((joins) && (pcnt > 1))
2164 // pars[1] already set up and containing key from blog2[j]
2169 pars[1] = parameters[1];
2175 fn(pars,pcnt-(end-start),u);
2184 void kill_link(userrec *user,const char* r)
2186 user_hash::iterator iter = clientlist.find(user->nick);
2188 char reason[MAXBUF];
2190 strncpy(reason,r,MAXBUF);
2192 if (strlen(reason)>MAXQUIT)
2194 reason[MAXQUIT-1] = '\0';
2197 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2198 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2199 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
2201 if (user->registered == 7) {
2202 FOREACH_MOD OnUserQuit(user);
2203 WriteCommonExcept(user,"QUIT :%s",reason);
2205 // Q token must go to ALL servers!!!
2206 char buffer[MAXBUF];
2207 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2208 NetSendToAll(buffer);
2211 FOREACH_MOD OnUserDisconnect(user);
2215 FOREACH_MOD OnRawSocketClose(user->fd);
2216 shutdown(user->fd,2);
2220 if (user->registered == 7) {
2221 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2225 if (user->registered == 7) {
2226 purge_empty_chans(user);
2229 if (iter != clientlist.end())
2231 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
2233 fd_ref_table[user->fd] = NULL;
2235 clientlist.erase(iter);
2239 void kill_link_silent(userrec *user,const char* r)
2241 user_hash::iterator iter = clientlist.find(user->nick);
2243 char reason[MAXBUF];
2245 strncpy(reason,r,MAXBUF);
2247 if (strlen(reason)>MAXQUIT)
2249 reason[MAXQUIT-1] = '\0';
2252 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2253 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2254 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
2256 if (user->registered == 7) {
2257 FOREACH_MOD OnUserQuit(user);
2258 WriteCommonExcept(user,"QUIT :%s",reason);
2260 // Q token must go to ALL servers!!!
2261 char buffer[MAXBUF];
2262 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2263 NetSendToAll(buffer);
2266 FOREACH_MOD OnUserDisconnect(user);
2270 FOREACH_MOD OnRawSocketClose(user->fd);
2271 shutdown(user->fd,2);
2275 if (user->registered == 7) {
2276 purge_empty_chans(user);
2279 if (iter != clientlist.end())
2281 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
2283 fd_ref_table[user->fd] = NULL;
2285 clientlist.erase(iter);
2291 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2293 char* Passwd(userrec *user)
2295 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2297 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2305 bool IsDenied(userrec *user)
2307 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2309 if (match(user->host,i->host) && (i->type == CC_DENY))
2320 /* sends out an error notice to all connected clients (not to be used
2323 void send_error(char *s)
2325 log(DEBUG,"send_error: %s",s);
2326 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2328 if (isnick(i->second->nick))
2330 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2334 // fix - unregistered connections receive ERROR, not NOTICE
2335 Write(i->second->fd,"ERROR :%s",s);
2340 void Error(int status)
2342 signal (SIGALRM, SIG_IGN);
2343 signal (SIGPIPE, SIG_IGN);
2344 signal (SIGTERM, SIG_IGN);
2345 signal (SIGABRT, SIG_IGN);
2346 signal (SIGSEGV, SIG_IGN);
2347 signal (SIGURG, SIG_IGN);
2348 signal (SIGKILL, SIG_IGN);
2349 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
2350 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2355 int main(int argc, char **argv)
2359 log(DEBUG,"*** InspIRCd starting up!");
2360 if (!FileExists(CONFIG_FILE))
2362 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2363 log(DEFAULT,"main: no config");
2364 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2368 for (int i = 1; i < argc; i++)
2370 if (!strcmp(argv[i],"-nofork")) {
2373 if (!strcmp(argv[i],"-wait")) {
2376 if (!strcmp(argv[i],"-nolimit")) {
2381 strlcpy(MyExecutable,argv[0],MAXBUF);
2383 if (InspIRCd() == ERROR)
2385 log(DEFAULT,"main: daemon function bailed");
2386 printf("ERROR: could not initialise. Shutting down.\n");
2393 template<typename T> inline string ConvToStr(const T &in)
2396 if (!(tmp << in)) return string();
2400 /* re-allocates a nick in the user_hash after they change nicknames,
2401 * returns a pointer to the new user as it may have moved */
2403 userrec* ReHashNick(char* Old, char* New)
2405 //user_hash::iterator newnick;
2406 user_hash::iterator oldnick = clientlist.find(Old);
2408 log(DEBUG,"ReHashNick: %s %s",Old,New);
2410 if (!strcasecmp(Old,New))
2412 log(DEBUG,"old nick is new nick, skipping");
2413 return oldnick->second;
2416 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2418 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2420 clientlist[New] = new userrec();
2421 clientlist[New] = oldnick->second;
2422 clientlist.erase(oldnick);
2424 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2426 return clientlist[New];
2429 /* adds or updates an entry in the whowas list */
2430 void AddWhoWas(userrec* u)
2432 user_hash::iterator iter = whowas.find(u->nick);
2433 userrec *a = new userrec();
2434 strlcpy(a->nick,u->nick,NICKMAX);
2435 strlcpy(a->ident,u->ident,64);
2436 strlcpy(a->dhost,u->dhost,256);
2437 strlcpy(a->host,u->host,256);
2438 strlcpy(a->fullname,u->fullname,128);
2439 strlcpy(a->server,u->server,256);
2440 a->signon = u->signon;
2442 /* MAX_WHOWAS: max number of /WHOWAS items
2443 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2444 * can be replaced by a newer one
2447 if (iter == whowas.end())
2449 if (whowas.size() == WHOWAS_MAX)
2451 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2453 // 3600 seconds in an hour ;)
2454 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
2456 if (i->second) delete i->second;
2458 log(DEBUG,"added WHOWAS entry, purged an old record");
2465 log(DEBUG,"added fresh WHOWAS entry");
2466 whowas[a->nick] = a;
2471 log(DEBUG,"updated WHOWAS entry");
2472 if (iter->second) delete iter->second;
2478 /* add a client connection to the sockets list */
2479 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2483 user_hash::iterator iter;
2485 tempnick = ConvToStr(socket) + "-unknown";
2486 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
2488 iter = clientlist.find(tempnick);
2491 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
2492 // using one as a registered connection. As theyre per fd, we can also safely assume
2493 // that we wont have collisions. Therefore, if the nick exists in the list, its only
2494 // used by a dead socket, erase the iterator so that the new client may reclaim it.
2495 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
2496 // issue in earlier alphas/betas
2497 if (iter != clientlist.end())
2499 clientlist.erase(iter);
2503 * It is OK to access the value here this way since we know
2504 * it exists, we just created it above.
2506 * At NO other time should you access a value in a map or a
2507 * hash_map this way.
2509 clientlist[tempnick] = new userrec();
2511 NonBlocking(socket);
2512 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
2514 clientlist[tempnick]->fd = socket;
2515 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2516 strncpy(clientlist[tempnick]->host, host,160);
2517 strncpy(clientlist[tempnick]->dhost, host,160);
2518 strncpy(clientlist[tempnick]->server, ServerName,256);
2519 strncpy(clientlist[tempnick]->ident, "unknown",12);
2520 clientlist[tempnick]->registered = 0;
2521 clientlist[tempnick]->signon = TIME+dns_timeout;
2522 clientlist[tempnick]->lastping = 1;
2523 clientlist[tempnick]->port = port;
2524 strncpy(clientlist[tempnick]->ip,ip,32);
2526 // set the registration timeout for this user
2527 unsigned long class_regtimeout = 90;
2528 int class_flood = 0;
2529 long class_threshold = 5;
2531 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2533 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2535 class_regtimeout = (unsigned long)i->registration_timeout;
2536 class_flood = i->flood;
2537 clientlist[tempnick]->pingmax = i->pingtime;
2538 class_threshold = i->threshold;
2543 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
2544 clientlist[tempnick]->timeout = TIME+class_regtimeout;
2545 clientlist[tempnick]->flood = class_flood;
2546 clientlist[tempnick]->threshold = class_threshold;
2548 for (int i = 0; i < MAXCHANS; i++)
2550 clientlist[tempnick]->chans[i].channel = NULL;
2551 clientlist[tempnick]->chans[i].uc_modes = 0;
2554 if (clientlist.size() == MAXCLIENTS)
2556 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2560 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
2561 // its a pretty big but for the moment valid assumption:
2562 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
2563 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
2564 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
2565 // which for the time being is a physical impossibility (even the largest networks dont have more
2566 // than about 10,000 users on ONE server!)
2569 kill_link(clientlist[tempnick],"Server is full");
2574 char* e = matches_exception(ip);
2577 char* r = matches_zline(ip);
2580 char reason[MAXBUF];
2581 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2582 kill_link(clientlist[tempnick],reason);
2586 fd_ref_table[socket] = clientlist[tempnick];
2589 // this function counts all users connected, wether they are registered or NOT.
2592 return clientlist.size();
2595 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
2596 int registered_usercount(void)
2599 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2601 if ((i->second->fd) && (isnick(i->second->nick))) c++;
2606 int usercount_invisible(void)
2610 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2612 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2617 int usercount_opers(void)
2621 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2623 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2628 int usercount_unknown(void)
2632 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2634 if ((i->second->fd) && (i->second->registered != 7))
2640 long chancount(void)
2642 return chanlist.size();
2645 long count_servs(void)
2648 for (int i = 0; i < 32; i++)
2652 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2654 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2664 long servercount(void)
2666 return count_servs()+1;
2672 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2674 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2680 void ShowMOTD(userrec *user)
2682 std::string WholeMOTD = "";
2685 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2688 WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2689 for (int i = 0; i != MOTD.size(); i++)
2691 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2693 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2694 // only one write operation
2695 send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
2696 statsSent += WholeMOTD.length();
2699 void ShowRULES(userrec *user)
2703 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2706 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2707 for (int i = 0; i != RULES.size(); i++)
2709 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2711 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2714 /* shows the message of the day, and any other on-logon stuff */
2715 void FullConnectUser(userrec* user)
2718 user->registered = 7;
2719 user->idle_lastmsg = TIME;
2720 log(DEBUG,"ConnectUser: %s",user->nick);
2722 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
2724 kill_link(user,"Invalid password");
2729 kill_link(user,"Unauthorised connection");
2733 char match_against[MAXBUF];
2734 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2735 char* e = matches_exception(match_against);
2738 char* r = matches_gline(match_against);
2741 char reason[MAXBUF];
2742 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2743 kill_link_silent(user,reason);
2746 r = matches_kline(user->host);
2749 char reason[MAXBUF];
2750 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2751 kill_link_silent(user,reason);
2756 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2757 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2758 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2759 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2760 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2761 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2762 std::stringstream v;
2763 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2764 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2765 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2766 v << std::string(Network);
2767 std::string data005 = v.str();
2768 FOREACH_MOD On005Numeric(data005);
2769 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2770 // so i'd better split it :)
2771 std::stringstream out(data005);
2772 std::string token = "";
2773 std::string line5 = "";
2774 int token_counter = 0;
2778 line5 = line5 + token + " ";
2780 if ((token_counter >= 13) || (out.eof() == true))
2782 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2788 FOREACH_MOD OnUserConnect(user);
2789 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
2791 char buffer[MAXBUF];
2792 snprintf(buffer,MAXBUF,"N %lu %s %s %s %s +%s %s %s :%s",(unsigned long)user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2793 NetSendToAll(buffer);
2797 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
2798 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
2799 // registration timeout maximum seconds)
2800 bool AllModulesReportReady(userrec* user)
2802 for (int i = 0; i <= MODCOUNT; i++)
2804 int res = modules[i]->OnCheckReady(user);
2811 /* shows the message of the day, and any other on-logon stuff */
2812 void ConnectUser(userrec *user)
2814 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2815 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
2817 FullConnectUser(user);
2821 std::string GetVersionString()
2823 char Revision[] = "$Revision$";
2824 char versiondata[MAXBUF];
2825 char *s1 = Revision;
2827 char *v2 = strtok_r(s1," ",&savept);
2829 v2 = strtok_r(s1," ",&savept);
2831 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu)",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION);
2835 void handle_version(char **parameters, int pcnt, userrec *user)
2839 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
2843 if (match(ServerName,parameters[0]))
2845 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
2848 bool displayed = false, found = false;
2849 for (int j = 0; j < 32; j++)
2853 for (int x = 0; x < me[j]->connectors.size(); x++)
2855 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
2858 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
2861 WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
2867 if ((!displayed) && (found))
2869 WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
2872 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2878 // calls a handler function for a command
2880 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2882 for (int i = 0; i < cmdlist.size(); i++)
2884 if (!strcasecmp(cmdlist[i].command,commandname))
2886 if (cmdlist[i].handler_function)
2888 if (pcnt>=cmdlist[i].min_params)
2890 if (strchr(user->modes,cmdlist[i].flags_needed))
2892 cmdlist[i].handler_function(parameters,pcnt,user);
2900 void DoSplitEveryone()
2902 bool go_again = true;
2906 for (int i = 0; i < 32; i++)
2910 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2912 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2915 j->CloseConnection();
2916 me[i]->connectors.erase(j);
2924 log(DEBUG,"Removed server. Will remove clients...");
2925 // iterate through the userlist and remove all users on this server.
2926 // because we're dealing with a mesh, we dont have to deal with anything
2927 // "down-route" from this server (nice huh)
2929 char reason[MAXBUF];
2933 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2935 if (strcasecmp(u->second->server,ServerName))
2937 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2938 kill_link(u->second,reason);
2948 char islast(const char* s)
2951 for (int j = 0; j < 32; j++)
2955 for (int k = 0; k < me[j]->connectors.size(); k++)
2957 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2961 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2971 long map_count(const char* s)
2974 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2976 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2982 void force_nickchange(userrec* user,const char* newnick)
2989 FOREACH_RESULT(OnUserPreNick(user,newnick));
2992 kill_link(user,"Nickname collision");
2995 if (matches_qline(newnick))
2998 kill_link(user,"Nickname collision");
3006 strncpy(nick,newnick,MAXBUF);
3008 if (user->registered == 7)
3012 handle_nick(pars,1,user);
3018 int process_parameters(char **command_p,char *parameters)
3021 int q = strlen(parameters);
3024 /* no parameters, command_p invalid! */
3027 if (parameters[0] == ':')
3029 command_p[0] = parameters+1;
3034 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
3036 /* only one parameter */
3037 command_p[0] = parameters;
3038 if (parameters[0] == ':')
3040 if (strchr(parameters,' ') != NULL)
3048 command_p[j++] = parameters;
3049 for (int i = 0; i <= q; i++)
3051 if (parameters[i] == ' ')
3053 command_p[j++] = parameters+i+1;
3054 parameters[i] = '\0';
3055 if (command_p[j-1][0] == ':')
3057 *command_p[j-1]++; /* remove dodgy ":" */
3059 /* parameter like this marks end of the sequence */
3063 return j; /* returns total number of items in the list */
3066 void process_command(userrec *user, char* cmd)
3070 char *command_p[127];
3071 char p[MAXBUF], temp[MAXBUF];
3072 int j, items, cmd_found;
3074 for (int i = 0; i < 127; i++)
3075 command_p[i] = NULL;
3090 int total_params = 0;
3093 for (int q = 0; q < strlen(cmd)-1; q++)
3095 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
3098 // found a 'trailing', we dont count them after this.
3106 // another phidjit bug...
3107 if (total_params > 126)
3109 *(strchr(cmd,' ')) = '\0';
3110 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
3114 strlcpy(temp,cmd,MAXBUF);
3116 std::string tmp = cmd;
3117 for (int i = 0; i <= MODCOUNT; i++)
3119 std::string oldtmp = tmp;
3120 modules[i]->OnServerRaw(tmp,true,user);
3123 log(DEBUG,"A Module changed the input string!");
3124 log(DEBUG,"New string: %s",tmp.c_str());
3125 log(DEBUG,"Old string: %s",oldtmp.c_str());
3129 strlcpy(cmd,tmp.c_str(),MAXBUF);
3130 strlcpy(temp,cmd,MAXBUF);
3132 if (!strchr(cmd,' '))
3134 /* no parameters, lets skip the formalities and not chop up
3136 log(DEBUG,"About to preprocess command with no params");
3138 command_p[0] = NULL;
3140 for (int i = 0; i <= strlen(cmd); i++)
3142 cmd[i] = toupper(cmd[i]);
3150 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
3151 for (int i = 0; i < strlen(temp); i++)
3153 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
3159 /* split the full string into a command plus parameters */
3163 if (strchr(cmd,' '))
3165 for (int i = 0; i <= strlen(cmd); i++)
3167 /* capitalise the command ONLY, leave params intact */
3168 cmd[i] = toupper(cmd[i]);
3169 /* are we nearly there yet?! :P */
3173 parameters = cmd+i+1;
3181 for (int i = 0; i <= strlen(cmd); i++)
3183 cmd[i] = toupper(cmd[i]);
3190 if (strlen(command)>MAXCOMMAND)
3192 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
3196 for (int x = 0; x < strlen(command); x++)
3198 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
3200 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
3202 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
3205 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3212 for (int i = 0; i != cmdlist.size(); i++)
3214 if (cmdlist[i].command[0])
3216 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
3222 items = process_parameters(command_p,parameters);
3227 command_p[0] = NULL;
3233 command_p[0] = NULL;
3238 /* activity resets the ping pending timer */
3239 user->nping = TIME + user->pingmax;
3240 if ((items) < cmdlist[i].min_params)
3242 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
3243 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
3246 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
3248 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3249 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
3253 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
3255 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3256 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
3260 /* if the command isnt USER, PASS, or NICK, and nick is empty,
3262 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
3264 if ((!isnick(user->nick)) || (user->registered != 7))
3266 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3267 WriteServ(user->fd,"451 %s :You have not registered",command);
3271 if ((user->registered == 7) && (!strchr(user->modes,'o')))
3275 mycmd = strtok_r(DisabledCommands," ",&savept2);
3278 if (!strcasecmp(mycmd,command))
3280 // command is disabled!
3281 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
3284 mycmd = strtok_r(NULL," ",&savept2);
3289 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
3291 if (cmdlist[i].handler_function)
3294 /* ikky /stats counters */
3297 cmdlist[i].use_count++;
3298 cmdlist[i].total_bytes+=strlen(temp);
3302 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
3303 if (MOD_RESULT == 1) {
3307 /* WARNING: nothing may come after the
3308 * command handler call, as the handler
3309 * may free the user structure! */
3311 cmdlist[i].handler_function(command_p,items,user);
3317 WriteServ(user->fd,"451 %s :You have not registered",command);
3325 if ((!cmd_found) && (user))
3328 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3333 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
3336 /* create the command and push it onto the table */
3337 strlcpy(comm.command,cmd,MAXBUF);
3338 strlcpy(comm.source,source,MAXBUF);
3339 comm.handler_function = f;
3340 comm.flags_needed = flags;
3341 comm.min_params = minparams;
3343 comm.total_bytes = 0;
3344 cmdlist.push_back(comm);
3345 log(DEBUG,"Added command %s (%lu parameters)",cmd,(unsigned long)minparams);
3348 bool removecommands(const char* source)
3350 bool go_again = true;
3354 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
3356 if (!strcmp(i->source,source))
3358 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
3368 void SetupCommandTable(void)
3370 createcommand("USER",handle_user,0,4,"<core>");
3371 createcommand("NICK",handle_nick,0,1,"<core>");
3372 createcommand("QUIT",handle_quit,0,0,"<core>");
3373 createcommand("VERSION",handle_version,0,0,"<core>");
3374 createcommand("PING",handle_ping,0,1,"<core>");
3375 createcommand("PONG",handle_pong,0,1,"<core>");
3376 createcommand("ADMIN",handle_admin,0,0,"<core>");
3377 createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
3378 createcommand("INFO",handle_info,0,0,"<core>");
3379 createcommand("TIME",handle_time,0,0,"<core>");
3380 createcommand("WHOIS",handle_whois,0,1,"<core>");
3381 createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
3382 createcommand("NOTICE",handle_notice,0,2,"<core>");
3383 createcommand("JOIN",handle_join,0,1,"<core>");
3384 createcommand("NAMES",handle_names,0,0,"<core>");
3385 createcommand("PART",handle_part,0,1,"<core>");
3386 createcommand("KICK",handle_kick,0,2,"<core>");
3387 createcommand("MODE",handle_mode,0,1,"<core>");
3388 createcommand("TOPIC",handle_topic,0,1,"<core>");
3389 createcommand("WHO",handle_who,0,1,"<core>");
3390 createcommand("MOTD",handle_motd,0,0,"<core>");
3391 createcommand("RULES",handle_rules,0,0,"<core>");
3392 createcommand("OPER",handle_oper,0,2,"<core>");
3393 createcommand("LIST",handle_list,0,0,"<core>");
3394 createcommand("DIE",handle_die,'o',1,"<core>");
3395 createcommand("RESTART",handle_restart,'o',1,"<core>");
3396 createcommand("KILL",handle_kill,'o',2,"<core>");
3397 createcommand("REHASH",handle_rehash,'o',0,"<core>");
3398 createcommand("LUSERS",handle_lusers,0,0,"<core>");
3399 createcommand("STATS",handle_stats,0,1,"<core>");
3400 createcommand("USERHOST",handle_userhost,0,1,"<core>");
3401 createcommand("AWAY",handle_away,0,0,"<core>");
3402 createcommand("ISON",handle_ison,0,0,"<core>");
3403 createcommand("SUMMON",handle_summon,0,0,"<core>");
3404 createcommand("USERS",handle_users,0,0,"<core>");
3405 createcommand("INVITE",handle_invite,0,2,"<core>");
3406 createcommand("PASS",handle_pass,0,1,"<core>");
3407 createcommand("TRACE",handle_trace,'o',0,"<core>");
3408 createcommand("WHOWAS",handle_whowas,0,1,"<core>");
3409 createcommand("CONNECT",handle_connect,'o',1,"<core>");
3410 createcommand("SQUIT",handle_squit,'o',0,"<core>");
3411 createcommand("MODULES",handle_modules,0,0,"<core>");
3412 createcommand("LINKS",handle_links,0,0,"<core>");
3413 createcommand("MAP",handle_map,0,0,"<core>");
3414 createcommand("KLINE",handle_kline,'o',1,"<core>");
3415 createcommand("GLINE",handle_gline,'o',1,"<core>");
3416 createcommand("ZLINE",handle_zline,'o',1,"<core>");
3417 createcommand("QLINE",handle_qline,'o',1,"<core>");
3418 createcommand("ELINE",handle_eline,'o',1,"<core>");
3419 createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
3420 createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
3421 createcommand("SERVER",handle_server,0,0,"<core>");
3424 void process_buffer(const char* cmdbuf,userrec *user)
3428 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3434 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3441 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
3443 strlcpy(cmd,cmdbuf,MAXBUF);
3448 int sl = strlen(cmd)-1;
3449 if ((cmd[sl] == 13) || (cmd[sl] == 10))
3454 if ((cmd[sl] == 13) || (cmd[sl] == 10))
3459 while (cmd[sl] == ' ') // strip trailing spaces
3469 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
3471 if ((user) && (cmd))
3473 process_command(user,cmd);
3477 void DoSync(serverrec* serv, char* tcp_host)
3480 log(DEBUG,"Sending sync");
3481 // send start of sync marker: Y <timestamp>
3482 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3483 // except the ones its receiving it from.
3484 snprintf(data,MAXBUF,"Y %lu",(unsigned long)TIME);
3485 serv->SendPacket(data,tcp_host);
3486 // send users and channels
3488 NetSendMyRoutingTable();
3490 // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
3491 for (int j = 0; j < 32; j++)
3495 for (int k = 0; k < me[j]->connectors.size(); k++)
3497 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3499 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3500 serv->SendPacket(data,tcp_host);
3506 // send our version for the remote side to cache
3507 snprintf(data,MAXBUF,"v %s %s",ServerName,GetVersionString().c_str());
3508 serv->SendPacket(data,tcp_host);
3510 // sync the users and channels, give the modules a look-in.
3511 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3513 snprintf(data,MAXBUF,"N %lu %s %s %s %s +%s %s %s :%s",(unsigned long)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);
3514 serv->SendPacket(data,tcp_host);
3515 if (strchr(u->second->modes,'o'))
3517 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3518 serv->SendPacket(data,tcp_host);
3520 for (int i = 0; i <= MODCOUNT; i++)
3522 string_list l = modules[i]->OnUserSync(u->second);
3523 for (int j = 0; j < l.size(); j++)
3525 strlcpy(data,l[j].c_str(),MAXBUF);
3526 serv->SendPacket(data,tcp_host);
3529 char* chl = chlist(u->second);
3532 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chl);
3533 serv->SendPacket(data,tcp_host);
3536 // send channel modes, topics etc...
3537 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3539 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3540 serv->SendPacket(data,tcp_host);
3541 for (int i = 0; i <= MODCOUNT; i++)
3543 string_list l = modules[i]->OnChannelSync(c->second);
3544 for (int j = 0; j < l.size(); j++)
3546 strlcpy(data,l[j].c_str(),MAXBUF);
3547 serv->SendPacket(data,tcp_host);
3550 if (c->second->topic[0])
3552 snprintf(data,MAXBUF,"T %lu %s %s :%s",(unsigned long)c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3553 serv->SendPacket(data,tcp_host);
3555 // send current banlist
3557 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3559 snprintf(data,MAXBUF,"M %s +b %s",c->second->name,b->data);
3560 serv->SendPacket(data,tcp_host);
3563 // sync global zlines, glines, etc
3564 sync_xlines(serv,tcp_host);
3566 snprintf(data,MAXBUF,"F %lu",(unsigned long)TIME);
3567 serv->SendPacket(data,tcp_host);
3568 log(DEBUG,"Sent sync");
3569 // ircd sends its serverlist after the end of sync here
3573 void NetSendMyRoutingTable()
3575 // send out a line saying what is reachable to us.
3576 // E.g. if A is linked to B C and D, send out:
3578 // if its only linked to B and D send out:
3580 // if it has no links, dont even send out the line at all.
3581 char buffer[MAXBUF];
3582 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3583 bool sendit = false;
3584 for (int i = 0; i < 32; i++)
3588 for (int j = 0; j < me[i]->connectors.size(); j++)
3590 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3592 strlcat(buffer," ",MAXBUF);
3593 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3600 NetSendToAll(buffer);
3604 void DoSplit(const char* params)
3606 bool go_again = true;
3610 for (int i = 0; i < 32; i++)
3614 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3616 if (!strcasecmp(j->GetServerName().c_str(),params))
3619 j->CloseConnection();
3620 me[i]->connectors.erase(j);
3628 log(DEBUG,"Removed server. Will remove clients...");
3629 // iterate through the userlist and remove all users on this server.
3630 // because we're dealing with a mesh, we dont have to deal with anything
3631 // "down-route" from this server (nice huh)
3633 char reason[MAXBUF];
3634 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3638 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3640 if (!strcasecmp(u->second->server,params))
3642 kill_link(u->second,reason);
3650 // removes a server. Will NOT remove its users!
3652 void RemoveServer(const char* name)
3654 bool go_again = true;
3658 for (int i = 0; i < 32; i++)
3662 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3664 if (!strcasecmp(j->GetServerName().c_str(),name))
3667 j->CloseConnection();
3668 me[i]->connectors.erase(j);
3679 char MODERR[MAXBUF];
3686 void erase_factory(int j)
3689 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
3694 factory.push_back(NULL);
3701 void erase_module(int j)
3704 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
3710 modules.push_back(NULL);
3716 for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
3720 module_names.erase(v);
3728 bool UnloadModule(const char* filename)
3730 for (int j = 0; j != module_names.size(); j++)
3732 if (module_names[j] == std::string(filename))
3734 if (modules[j]->GetVersion().Flags & VF_STATIC)
3736 log(DEFAULT,"Failed to unload STATIC module %s",filename);
3737 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
3741 log(DEBUG,"Deleting module...");
3743 log(DEBUG,"Erasing module entry...");
3745 log(DEBUG,"Removing dependent commands...");
3746 removecommands(filename);
3747 log(DEFAULT,"Module %s unloaded",filename);
3752 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
3753 snprintf(MODERR,MAXBUF,"Module not loaded");
3757 bool DirValid(char* dirandfile)
3760 strlcpy(work,dirandfile,MAXBUF);
3761 int p = strlen(work);
3762 // we just want the dir
3763 while (strlen(work))
3772 char buffer[MAXBUF], otherdir[MAXBUF];
3773 // Get the current working directory
3774 if( getcwd( buffer, MAXBUF ) == NULL )
3777 if( getcwd( otherdir, MAXBUF ) == NULL )
3780 if (strlen(otherdir) >= strlen(work))
3782 otherdir[strlen(work)] = '\0';
3783 if (!strcmp(otherdir,work))
3792 bool LoadModule(const char* filename)
3794 char modfile[MAXBUF];
3795 snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
3796 if (!DirValid(modfile))
3798 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
3799 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
3802 log(DEBUG,"Loading module: %s",modfile);
3803 if (FileExists(modfile))
3805 for (int j = 0; j < module_names.size(); j++)
3807 if (module_names[j] == std::string(filename))
3809 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
3810 snprintf(MODERR,MAXBUF,"Module already loaded");
3814 ircd_module* a = new ircd_module(modfile);
3815 factory[MODCOUNT+1] = a;
3816 if (factory[MODCOUNT+1]->LastError())
3818 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
3819 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
3823 if (factory[MODCOUNT+1]->factory)
3825 Module* m = factory[MODCOUNT+1]->factory->CreateModule();
3826 modules[MODCOUNT+1] = m;
3827 /* save the module and the module's classfactory, if
3828 * this isnt done, random crashes can occur :/ */
3829 module_names.push_back(filename);
3833 log(DEFAULT,"Unable to load %s",modfile);
3834 snprintf(MODERR,MAXBUF,"Factory function failed!");
3840 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
3841 snprintf(MODERR,MAXBUF,"Module file could not be found");
3850 struct sockaddr_in client,server;
3851 char addrs[MAXBUF][255];
3852 int incomingSockfd, result = TRUE;
3855 int selectResult = 0, selectResult2 = 0;
3856 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3860 log_file = fopen("ircd.log","a+");
3863 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3867 log(DEFAULT,"$Id$");
3870 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3872 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
3874 SetupCommandTable();
3875 log(DEBUG,"InspIRCd: startup: default command table set up");
3877 ReadConfig(true,NULL);
3880 printf("WARNING: %s\n\n",DieValue);
3881 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3884 log(DEBUG,"InspIRCd: startup: read config");
3886 int clientportcount = 0, serverportcount = 0;
3888 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3890 ConfValue("bind","port",count,configToken,&config_f);
3891 ConfValue("bind","address",count,Addr,&config_f);
3892 ConfValue("bind","type",count,Type,&config_f);
3893 if (!strcmp(Type,"servers"))
3895 char Default[MAXBUF];
3896 strcpy(Default,"no");
3897 ConfValue("bind","default",count,Default,&config_f);
3898 if (strchr(Default,'y'))
3900 defaultRoute = serverportcount;
3901 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3903 me[serverportcount] = new serverrec(ServerName,100L,false);
3904 if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
3906 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
3907 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
3916 ports[clientportcount] = atoi(configToken);
3917 strlcpy(addrs[clientportcount],Addr,256);
3920 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3922 portCount = clientportcount;
3923 UDPportCount = serverportcount;
3925 log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)UDPportCount);
3926 log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
3930 /* BugFix By Craig! :p */
3932 for (count = 0; count < ConfValueEnum("module",&config_f); count++)
3934 ConfValue("module","name",count,configToken,&config_f);
3935 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
3936 if (!LoadModule(configToken))
3938 log(DEFAULT,"Exiting due to a module loader error.");
3939 printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
3943 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
3945 startup_time = time(NULL);
3948 ConfValue("pid","file",0,PID,&config_f);
3949 // write once here, to try it out and make sure its ok
3952 /* setup select call */
3953 FD_ZERO(&selectFds);
3954 log(DEBUG,"InspIRCd: startup: zero selects");
3955 log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
3957 for (count = 0; count < portCount; count++)
3959 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3961 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
3964 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3966 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
3968 else /* well we at least bound to one socket so we'll continue */
3974 log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
3976 /* if we didn't bind to anything then abort */
3977 if (boundPortCount == 0)
3979 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
3980 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
3985 printf("\nInspIRCd is now running!\n");
3989 log(VERBOSE,"Not forking as -nofork was specified");
3993 if (DaemonSeed() == ERROR)
3995 log(DEFAULT,"InspIRCd: startup: can't daemonise");
3996 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4003 length = sizeof (client);
4004 char udp_msg[MAXBUF],tcp_host[MAXBUF];
4008 tvs.tv_usec = 10000L;
4011 tv.tv_usec = 10000L;
4015 tval.tv_usec = 10000L;
4017 int total_in_this_set = 0;
4019 bool expire_run = false;
4021 /* main loop, this never returns */
4024 #ifdef _POSIX_PRIORITY_SCHEDULING
4031 // we only read time() once per iteration rather than tons of times!
4034 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4035 // them in a list, then reap the list every second or so.
4036 if (((TIME % 5) == 0) && (!expire_run))
4039 FOREACH_MOD OnBackgroundTimer(TIME);
4043 if ((TIME % 5) == 1)
4046 // fix by brain - this must be below any manipulation of the hashmap by modules
4047 user_hash::iterator count2 = clientlist.begin();
4049 FD_ZERO(&serverfds);
4051 for (int x = 0; x != UDPportCount; x++)
4054 FD_SET(me[x]->fd, &serverfds);
4057 // serverFds timevals went here
4059 tvs.tv_usec = 30000L;
4061 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
4064 for (int x = 0; x != UDPportCount; x++)
4066 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
4068 char remotehost[MAXBUF],resolved[MAXBUF];
4069 length = sizeof (client);
4070 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
4071 if (incomingSockfd != -1)
4073 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
4074 if(CleanAndResolve(resolved, remotehost) != TRUE)
4076 strlcpy(resolved,remotehost,MAXBUF);
4078 // add to this connections ircd_connector vector
4079 // *FIX* - we need the LOCAL port not the remote port in &client!
4080 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
4086 for (int x = 0; x < UDPportCount; x++)
4088 std::deque<std::string> msgs;
4090 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
4092 for (int ctr = 0; ctr < msgs.size(); ctr++)
4094 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
4095 log(DEBUG,"Processing: %s",udp_msg);
4098 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
4101 // during a netburst, send all data to all other linked servers
4102 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
4104 if (is_uline(tcp_host))
4106 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
4108 NetSendToAllExcept(tcp_host,udp_msg);
4112 NetSendToAllExcept(tcp_host,udp_msg);
4114 std::string msg = udp_msg;
4115 FOREACH_MOD OnPacketReceive(msg,tcp_host);
4116 strlcpy(udp_msg,msg.c_str(),MAXBUF);
4117 handle_link_packet(udp_msg, tcp_host, me[x]);
4124 while (count2 != clientlist.end())
4127 total_in_this_set = 0;
4129 user_hash::iterator xcount = count2;
4130 user_hash::iterator endingiter = count2;
4132 if (count2 == clientlist.end()) break;
4134 userrec* curr = NULL;
4137 curr = count2->second;
4139 if ((curr) && (curr->fd != 0))
4141 // assemble up to 64 sockets into an fd_set
4142 // to implement a pooling mechanism.
4144 // This should be up to 64x faster than the
4145 // old implementation.
4146 while (total_in_this_set < 64)
4148 if (count2 != clientlist.end())
4150 curr = count2->second;
4151 // we don't check the state of remote users.
4152 if ((curr->fd != -1) && (curr->fd != FD_MAGIC_NUMBER))
4154 FD_SET (curr->fd, &sfd);
4156 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
4157 // their connection class.
4158 if ((TIME > curr->timeout) && (curr->registered != 7))
4160 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
4161 kill_link(curr,"Registration timeout");
4164 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
4166 log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
4167 curr->dns_done = true;
4169 FullConnectUser(curr);
4172 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
4174 log(DEBUG,"dns done, registered=3, and modules ready, OK");
4175 FullConnectUser(curr);
4178 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
4180 if ((!curr->lastping) && (curr->registered == 7))
4182 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
4183 kill_link(curr,"Ping timeout");
4186 Write(curr->fd,"PING :%s",ServerName);
4187 log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
4189 curr->nping = TIME+curr->pingmax; // was hard coded to 120
4193 total_in_this_set++;
4198 endingiter = count2;
4199 count2 = xcount; // roll back to where we were
4203 // tvals defined here
4205 tval.tv_usec = 1000L;
4206 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
4208 // now loop through all of the items in this pool if any are waiting
4209 if (selectResult2 > 0)
4210 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
4213 #ifdef _POSIX_PRIORITY_SCHEDULING
4216 userrec* cu = count2a->second;
4218 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
4220 log(DEBUG,"Data waiting on socket %d",cu->fd);
4223 FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
4226 result = read(cu->fd, data, 65535);
4228 else result = result2;
4229 log(DEBUG,"Read result: %d",result);
4233 statsRecv += result;
4234 // perform a check on the raw buffer as an array (not a string!) to remove
4235 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
4236 // hopefully this should stop even more people whining about "Unknown command: *"
4237 for (int checker = 0; checker < result; checker++)
4239 if ((data[checker] == 0) || (data[checker] == 7))
4240 data[checker] = ' ';
4243 data[result] = '\0';
4244 userrec* current = cu;
4245 int currfd = current->fd;
4247 // add the data to the users buffer
4248 if (!current->AddBuffer(data))
4250 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
4251 if (current->registered == 7)
4253 kill_link(current,"RecvQ exceeded");
4257 WriteOpers("*** Excess flood from %s",current->ip);
4258 log(DEFAULT,"Excess flood from: %s",current->ip);
4259 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
4264 if (current->recvq.length() > NetBufferSize)
4266 if (current->registered == 7)
4268 kill_link(current,"RecvQ exceeded");
4272 WriteOpers("*** Excess flood from %s",current->ip);
4273 log(DEFAULT,"Excess flood from: %s",current->ip);
4274 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
4279 // while there are complete lines to process...
4280 while (current->BufferIsReady())
4283 if (TIME > current->reset_due)
4285 current->reset_due = TIME + current->threshold;
4286 current->lines_in = 0;
4288 current->lines_in++;
4289 if (current->lines_in > current->flood)
4291 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4292 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4293 kill_link(current,"Excess flood");
4296 if ((floodlines > current->flood) && (current->flood != 0))
4298 if (current->registered == 7)
4300 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4301 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4302 kill_link(current,"Excess flood");
4306 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
4311 char sanitized[MAXBUF];
4312 // use GetBuffer to copy single lines into the sanitized string
4313 std::string single_line = current->GetBuffer();
4314 current->bytes_in += single_line.length();
4316 if (single_line.length()>512)
4318 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4319 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
4320 kill_link(current,"Excess flood");
4323 strlcpy(sanitized,single_line.c_str(),MAXBUF);
4326 // we're gonna re-scan to check if the nick is gone, after every
4327 // command - if it has, we're gonna bail
4328 process_buffer(sanitized,current);
4329 // look for the user's record in case it's changed... if theyve quit,
4330 // we cant do anything more with their buffer, so bail.
4331 // there used to be an ugly, slow loop here. Now we have a reference
4332 // table, life is much easier (and FASTER)
4333 if (!fd_ref_table[currfd])
4341 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
4343 log(DEBUG,"killing: %s",cu->nick);
4344 kill_link(cu,strerror(errno));
4348 // result EAGAIN means nothing read
4349 if (result == EAGAIN)
4357 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
4358 kill_link(cu,"Client exited");
4359 // must bail here? kill_link removes the hash, corrupting the iterator
4360 log(DEBUG,"Bailing from client exit");
4364 else if (result > 0)
4369 for (int q = 0; q < total_in_this_set; q++)
4375 #ifdef _POSIX_PRIORITY_SCHEDULING
4379 // set up select call
4380 for (count = 0; count < boundPortCount; count++)
4382 FD_SET (openSockfd[count], &selectFds);
4385 tv.tv_usec = 30000L;
4386 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4388 /* select is reporting a waiting socket. Poll them all to find out which */
4389 if (selectResult > 0)
4391 char target[MAXBUF], resolved[MAXBUF];
4392 for (count = 0; count < boundPortCount; count++)
4394 if (FD_ISSET (openSockfd[count], &selectFds))
4396 length = sizeof (client);
4397 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4399 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4400 strlcpy (resolved, target, MAXBUF);
4402 if (incomingSockfd < 0)
4404 WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
4405 log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
4410 FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
4412 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
4413 log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
4421 #ifdef _POSIX_PRIORITY_SCHEDULING
4426 close (incomingSockfd);