1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
46 #include "connection.h"
58 #include "inspstring.h"
62 #define nspace __gnu_cxx
67 int LogLevel = DEFAULT;
68 char ServerName[MAXBUF];
70 char ServerDesc[MAXBUF];
71 char AdminName[MAXBUF];
72 char AdminEmail[MAXBUF];
73 char AdminNick[MAXBUF];
75 char restartpass[MAXBUF];
79 char PrefixQuit[MAXBUF];
80 char DieValue[MAXBUF];
81 char DNSServer[MAXBUF];
83 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
84 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
86 time_t startup_time = time(NULL);
87 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
88 extern int MaxWhoResults;
92 bool AllowHalfop = true;
93 bool AllowProtect = true;
94 bool AllowFounder = true;
96 extern std::vector<Module*> modules;
97 std::vector<std::string> module_names;
98 extern std::vector<ircd_module*> factory;
99 std::vector<int> fd_reap;
102 int openSockfd[MAXSOCKS];
108 template<> struct hash<in_addr>
110 template<> struct nspace::hash<in_addr>
113 size_t operator()(const struct in_addr &a) const
116 memcpy(&q,&a,sizeof(size_t));
121 template<> struct hash<string>
123 template<> struct nspace::hash<string>
126 size_t operator()(const string &s) const
129 static struct hash<const char *> strhash;
130 strlcpy(a,s.c_str(),MAXBUF);
141 bool operator()(const string& s1, const string& s2) const
143 char a[MAXBUF],b[MAXBUF];
144 strlcpy(a,s1.c_str(),MAXBUF);
145 strlcpy(b,s2.c_str(),MAXBUF);
146 return (strcasecmp(a,b) == 0);
151 struct InAddr_HashComp
154 bool operator()(const in_addr &s1, const in_addr &s2) const
159 memcpy(&q,&s1,sizeof(size_t));
160 memcpy(&p,&s2,sizeof(size_t));
168 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
169 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
170 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
171 typedef std::deque<command_t> command_table;
177 user_hash clientlist;
180 command_table cmdlist;
187 struct linger linger = { 0 };
188 char MyExecutable[1024];
189 int boundPortCount = 0;
190 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
191 int defaultRoute = 0;
195 long MyKey = C.GenKey();
199 int has_channel(userrec *u, chanrec *c);
200 int usercount(chanrec *c);
201 int usercount_i(chanrec *c);
202 char* Passwd(userrec *user);
203 bool IsDenied(userrec *user);
204 void AddWhoWas(userrec* u);
206 std::vector<long> auth_cookies;
207 std::stringstream config_f(stringstream::in | stringstream::out);
213 char Revision[] = "$Revision$";
216 char *v1 = strtok_r(s1," ",&savept);
218 char *v2 = strtok_r(s1," ",&savept);
220 return (long)(atof(v2)*10000);
224 std::string getservername()
229 std::string getserverdesc()
234 std::string getnetworkname()
239 std::string getadminname()
244 std::string getadminemail()
249 std::string getadminnick()
254 void log(int level,char *text, ...)
256 char textbuffer[MAXBUF];
259 struct tm * timeinfo;
260 if (level < LogLevel)
264 timeinfo = localtime (&rawtime);
269 va_start (argsPtr, text);
270 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
272 strlcpy(b,asctime(timeinfo),MAXBUF);
273 b[strlen(b)-1] = ':';
274 fprintf(log_file,"%s %s\n",b,textbuffer);
277 // nofork enabled? display it on terminal too
278 printf("%s %s\n",b,textbuffer);
283 void readfile(file_cache &F, const char* fname)
286 char linebuf[MAXBUF];
288 log(DEBUG,"readfile: loading %s",fname);
290 file = fopen(fname,"r");
295 fgets(linebuf,sizeof(linebuf),file);
296 linebuf[strlen(linebuf)-1]='\0';
297 if (!strcmp(linebuf,""))
303 F.push_back(linebuf);
310 log(DEBUG,"readfile: failed to load file: %s",fname);
312 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
315 void ReadConfig(bool bail, userrec* user)
317 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
318 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF];
320 std::stringstream errstr;
322 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
327 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
335 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
336 while (!errstr.eof())
338 errstr.getline(dataline,1024);
339 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
344 WriteOpers("There were errors in the configuration file:",user->nick);
345 while (!errstr.eof())
347 errstr.getline(dataline,1024);
348 WriteOpers(dataline);
355 ConfValue("server","name",0,ServerName,&config_f);
356 ConfValue("server","description",0,ServerDesc,&config_f);
357 ConfValue("server","network",0,Network,&config_f);
358 ConfValue("admin","name",0,AdminName,&config_f);
359 ConfValue("admin","email",0,AdminEmail,&config_f);
360 ConfValue("admin","nick",0,AdminNick,&config_f);
361 ConfValue("files","motd",0,motd,&config_f);
362 ConfValue("files","rules",0,rules,&config_f);
363 ConfValue("power","diepass",0,diepass,&config_f);
364 ConfValue("power","pause",0,pauseval,&config_f);
365 ConfValue("power","restartpass",0,restartpass,&config_f);
366 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
367 ConfValue("die","value",0,DieValue,&config_f);
368 ConfValue("options","loglevel",0,dbg,&config_f);
369 ConfValue("options","netbuffersize",0,NB,&config_f);
370 ConfValue("options","maxwho",0,MW,&config_f);
371 ConfValue("options","allowhalfop",0,AH,&config_f);
372 ConfValue("options","allowprotect",0,AP,&config_f);
373 ConfValue("options","allowfounder",0,AF,&config_f);
374 ConfValue("dns","server",0,DNSServer,&config_f);
375 ConfValue("dns","timeout",0,DNT,&config_f);
376 NetBufferSize = atoi(NB);
377 MaxWhoResults = atoi(MW);
378 dns_timeout = atoi(DNT);
381 if (!strcmp(DNSServer,""))
382 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
383 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
384 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
385 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
386 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
388 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
389 NetBufferSize = 10240;
391 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
393 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
396 if (!strcmp(dbg,"debug"))
398 if (!strcmp(dbg,"verbose"))
400 if (!strcmp(dbg,"default"))
402 if (!strcmp(dbg,"sparse"))
404 if (!strcmp(dbg,"none"))
407 log(DEFAULT,"Reading message of the day...");
408 readfile(RULES,rules);
409 log(DEFAULT,"Reading connect classes...");
411 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
414 ConfValue("connect","allow",i,Value,&config_f);
415 ConfValue("connect","timeout",i,timeout,&config_f);
416 ConfValue("connect","flood",i,flood,&config_f);
417 if (strcmp(Value,""))
419 strlcpy(c.host,Value,MAXBUF);
421 strlcpy(Value,"",MAXBUF);
422 ConfValue("connect","password",i,Value,&config_f);
423 strlcpy(c.pass,Value,MAXBUF);
424 c.registration_timeout = 90; // default is 2 minutes
425 c.flood = atoi(flood);
428 c.registration_timeout = atoi(timeout);
430 Classes.push_back(c);
431 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
435 ConfValue("connect","deny",i,Value,&config_f);
436 strlcpy(c.host,Value,MAXBUF);
438 Classes.push_back(c);
439 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
443 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
444 read_xline_defaults();
445 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
447 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
450 /* write formatted text to a socket, in same format as printf */
452 void Write(int sock,char *text, ...)
456 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
459 char textbuffer[MAXBUF];
463 va_start (argsPtr, text);
464 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
466 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
470 write(sock,tb,strlen(tb));
474 /* write a server formatted numeric response to a single socket */
476 void WriteServ(int sock, char* text, ...)
480 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
483 char textbuffer[MAXBUF],tb[MAXBUF];
485 va_start (argsPtr, text);
487 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
489 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
493 write(sock,tb,strlen(tb));
497 /* write text from an originating user to originating user */
499 void WriteFrom(int sock, userrec *user,char* text, ...)
501 if ((!text) || (!user))
503 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
506 char textbuffer[MAXBUF],tb[MAXBUF];
508 va_start (argsPtr, text);
510 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
512 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
516 write(sock,tb,strlen(tb));
520 /* write text to an destination user from a source user (e.g. user privmsg) */
522 void WriteTo(userrec *source, userrec *dest,char *data, ...)
524 if ((!dest) || (!data))
526 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
529 char textbuffer[MAXBUF],tb[MAXBUF];
531 va_start (argsPtr, data);
532 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
536 // if no source given send it from the server.
539 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
543 WriteFrom(dest->fd,source,"%s",textbuffer);
547 /* write formatted text from a source user to all users on a channel
548 * including the sender (NOT for privmsg, notice etc!) */
550 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
552 if ((!Ptr) || (!user) || (!text))
554 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
557 char textbuffer[MAXBUF];
559 va_start (argsPtr, text);
560 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
562 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
564 if (has_channel(i->second,Ptr))
566 WriteTo(user,i->second,"%s",textbuffer);
571 /* write formatted text from a source user to all users on a channel
572 * including the sender (NOT for privmsg, notice etc!) doesnt send to
573 * users on remote servers */
575 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
577 if ((!Ptr) || (!text))
579 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
582 char textbuffer[MAXBUF];
584 va_start (argsPtr, text);
585 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
587 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
589 if (has_channel(i->second,Ptr))
591 if (i->second->fd != -1)
595 WriteServ(i->second->fd,"%s",textbuffer);
599 WriteTo(user,i->second,"%s",textbuffer);
607 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
609 if ((!Ptr) || (!user) || (!text))
611 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
614 char textbuffer[MAXBUF];
616 va_start (argsPtr, text);
617 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
619 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
623 if (has_channel(i->second,Ptr))
625 WriteServ(i->second->fd,"%s",textbuffer);
632 /* write formatted text from a source user to all users on a channel except
633 * for the sender (for privmsg etc) */
635 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
637 if ((!Ptr) || (!user) || (!text))
639 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
642 char textbuffer[MAXBUF];
644 va_start (argsPtr, text);
645 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
648 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
652 if (has_channel(i->second,Ptr) && (user != i->second))
654 WriteTo(user,i->second,"%s",textbuffer);
661 std::string GetServerDescription(char* servername)
663 for (int j = 0; j < 32; j++)
667 for (int k = 0; k < me[j]->connectors.size(); k++)
669 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
671 return me[j]->connectors[k].GetDescription();
675 return ServerDesc; // not a remote server that can be found, it must be me.
680 /* write a formatted string to all users who share at least one common
681 * channel, including the source user e.g. for use in NICK */
683 void WriteCommon(userrec *u, char* text, ...)
687 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
691 if (u->registered != 7) {
692 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
696 char textbuffer[MAXBUF];
698 va_start (argsPtr, text);
699 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
702 WriteFrom(u->fd,u,"%s",textbuffer);
704 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
708 if (common_channels(u,i->second) && (i->second != u))
710 WriteFrom(i->second->fd,u,"%s",textbuffer);
716 /* write a formatted string to all users who share at least one common
717 * channel, NOT including the source user e.g. for use in QUIT */
719 void WriteCommonExcept(userrec *u, char* text, ...)
723 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
727 if (u->registered != 7) {
728 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
732 char textbuffer[MAXBUF];
734 va_start (argsPtr, text);
735 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
738 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
742 if ((common_channels(u,i->second)) && (u != i->second))
744 WriteFrom(i->second->fd,u,"%s",textbuffer);
750 void WriteOpers(char* text, ...)
754 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
758 char textbuffer[MAXBUF];
760 va_start (argsPtr, text);
761 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
764 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
768 if (strchr(i->second->modes,'o'))
770 if (strchr(i->second->modes,'s'))
772 // send server notices to all with +s
773 // (TODO: needs SNOMASKs)
774 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
781 // returns TRUE of any users on channel C occupy server 'servername'.
783 bool ChanAnyOnThisServer(chanrec *c,char* servername)
785 log(DEBUG,"ChanAnyOnThisServer");
786 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
788 if (has_channel(i->second,c))
790 if (!strcasecmp(i->second->server,servername))
799 // returns true if user 'u' shares any common channels with any users on server 'servername'
801 bool CommonOnThisServer(userrec* u,const char* servername)
803 log(DEBUG,"ChanAnyOnThisServer");
804 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
806 if ((common_channels(u,i->second)) && (u != i->second))
808 if (!strcasecmp(i->second->server,servername))
810 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
819 void NetSendToCommon(userrec* u, char* s)
822 snprintf(buffer,MAXBUF,"%s",s);
824 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
826 for (int j = 0; j < 32; j++)
830 for (int k = 0; k < me[j]->connectors.size(); k++)
832 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
834 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
842 void NetSendToAll(char* s)
845 snprintf(buffer,MAXBUF,"%s",s);
847 log(DEBUG,"NetSendToAll: '%s'",s);
849 for (int j = 0; j < 32; j++)
853 for (int k = 0; k < me[j]->connectors.size(); k++)
855 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
861 void NetSendToAllAlive(char* s)
864 snprintf(buffer,MAXBUF,"%s",s);
866 log(DEBUG,"NetSendToAllAlive: '%s'",s);
868 for (int j = 0; j < 32; j++)
872 for (int k = 0; k < me[j]->connectors.size(); k++)
874 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
876 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
880 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
888 void NetSendToOne(char* target,char* s)
891 snprintf(buffer,MAXBUF,"%s",s);
893 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
895 for (int j = 0; j < 32; j++)
899 for (int k = 0; k < me[j]->connectors.size(); k++)
901 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
903 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
910 void NetSendToAllExcept(const char* target,char* s)
913 snprintf(buffer,MAXBUF,"%s",s);
915 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
917 for (int j = 0; j < 32; j++)
921 for (int k = 0; k < me[j]->connectors.size(); k++)
923 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
925 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
933 void WriteMode(const char* modes, int flags, const char* text, ...)
935 if ((!text) || (!modes) || (!flags))
937 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
941 char textbuffer[MAXBUF];
943 va_start (argsPtr, text);
944 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
947 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
951 bool send_to_user = false;
956 for (int n = 0; n < strlen(modes); n++)
958 if (!hasumode(i->second,modes[n]))
960 send_to_user = false;
965 else if (flags == WM_OR)
967 send_to_user = false;
968 for (int n = 0; n < strlen(modes); n++)
970 if (hasumode(i->second,modes[n]))
980 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
987 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
989 if ((!text) || (!source))
991 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
996 char textbuffer[MAXBUF];
998 va_start (argsPtr, text);
999 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1002 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1006 if (strchr(i->second->modes,'w'))
1008 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1015 char buffer[MAXBUF];
1016 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1017 NetSendToAll(buffer);
1021 /* convert a string to lowercase. Note following special circumstances
1022 * taken from RFC 1459. Many "official" server branches still hold to this
1023 * rule so i will too;
1025 * Because of IRC's scandanavian origin, the characters {}| are
1026 * considered to be the lower case equivalents of the characters []\,
1027 * respectively. This is a critical issue when determining the
1028 * equivalence of two nicknames.
1031 void strlower(char *n)
1037 for (int i = 0; i != strlen(n); i++)
1039 n[i] = tolower(n[i]);
1051 /* Find a user record by nickname and return a pointer to it */
1053 userrec* Find(std::string nick)
1055 user_hash::iterator iter = clientlist.find(nick);
1057 if (iter == clientlist.end())
1058 /* Couldn't find it */
1061 return iter->second;
1064 /* find a channel record by channel name and return a pointer to it */
1066 chanrec* FindChan(const char* chan)
1070 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1074 chan_hash::iterator iter = chanlist.find(chan);
1076 if (iter == chanlist.end())
1077 /* Couldn't find it */
1080 return iter->second;
1084 long GetMaxBans(char* name)
1087 for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1089 ConfValue("banlist","chan",count,CM,&config_f);
1092 ConfValue("banlist","limit",count,CM,&config_f);
1100 void purge_empty_chans(void)
1102 int go_again = 1, purge = 0;
1107 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1110 if (!usercount(i->second))
1112 /* kill the record */
1113 if (i != chanlist.end())
1115 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1116 if (i->second) delete i->second;
1125 log(DEBUG,"skipped purge for %s",i->second->name);
1130 log(DEBUG,"completed channel purge, killed %d",purge);
1134 char scratch[MAXBUF];
1135 char sparam[MAXBUF];
1137 char* chanmodes(chanrec *chan)
1141 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1148 if (chan->noexternal)
1150 strlcat(scratch,"n",MAXMODES);
1152 if (chan->topiclock)
1154 strlcat(scratch,"t",MAXMODES);
1156 if (strcmp(chan->key,""))
1158 strlcat(scratch,"k",MAXMODES);
1162 strlcat(scratch,"l",MAXMODES);
1164 if (chan->inviteonly)
1166 strlcat(scratch,"i",MAXMODES);
1168 if (chan->moderated)
1170 strlcat(scratch,"m",MAXMODES);
1174 strlcat(scratch,"s",MAXMODES);
1176 if (chan->c_private)
1178 strlcat(scratch,"p",MAXMODES);
1180 if (strcmp(chan->key,""))
1182 strlcat(sparam," ",MAXBUF);
1183 strlcat(sparam,chan->key,MAXBUF);
1188 sprintf(foo," %d",chan->limit);
1189 strlcat(sparam,foo,MAXBUF);
1191 if (strlen(chan->custom_modes))
1193 strlcat(scratch,chan->custom_modes,MAXMODES);
1194 for (int z = 0; z < strlen(chan->custom_modes); z++)
1196 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1199 strlcat(sparam," ",MAXBUF);
1200 strlcat(sparam,extparam.c_str(),MAXBUF);
1204 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1205 strlcat(scratch,sparam,MAXMODES);
1210 /* compile a userlist of a channel into a string, each nick seperated by
1211 * spaces and op, voice etc status shown as @ and + */
1213 void userlist(userrec *user,chanrec *c)
1215 if ((!c) || (!user))
1217 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1221 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1222 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1224 if (has_channel(i->second,c))
1226 if (isnick(i->second->nick))
1228 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1230 /* user is +i, and source not on the channel, does not show
1231 * nick in NAMES list */
1234 strlcat(list,cmode(i->second,c),MAXBUF);
1235 strlcat(list,i->second->nick,MAXBUF);
1236 strlcat(list," ",MAXBUF);
1237 if (strlen(list)>(480-NICKMAX))
1239 /* list overflowed into
1240 * multiple numerics */
1241 WriteServ(user->fd,"%s",list);
1242 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1247 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1249 WriteServ(user->fd,"%s",list);
1253 /* return a count of the users on a specific channel accounting for
1254 * invisible users who won't increase the count. e.g. for /LIST */
1256 int usercount_i(chanrec *c)
1263 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1268 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1272 if (has_channel(i->second,c))
1274 if (isnick(i->second->nick))
1276 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1278 /* user is +i, and source not on the channel, does not show
1279 * nick in NAMES list */
1287 log(DEBUG,"usercount_i: %s %d",c->name,count);
1292 int usercount(chanrec *c)
1299 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1304 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1308 if (has_channel(i->second,c))
1310 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1317 log(DEBUG,"usercount: %s %d",c->name,count);
1322 /* add a channel to a user, creating the record for it if needed and linking
1323 * it to the user record */
1325 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1327 if ((!user) || (!cn))
1329 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1338 strncpy(cname,cn,MAXBUF);
1340 // we MUST declare this wherever we use FOREACH_RESULT
1343 if (strlen(cname) > CHANMAX-1)
1345 cname[CHANMAX-1] = '\0';
1348 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1350 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1352 return NULL; // already on the channel!
1356 if (!FindChan(cname))
1359 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1360 if (MOD_RESULT == 1) {
1364 /* create a new one */
1365 log(DEBUG,"add_channel: creating: %s",cname);
1367 chanlist[cname] = new chanrec();
1369 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1370 chanlist[cname]->topiclock = 1;
1371 chanlist[cname]->noexternal = 1;
1372 chanlist[cname]->created = time(NULL);
1373 strcpy(chanlist[cname]->topic, "");
1374 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1375 chanlist[cname]->topicset = 0;
1376 Ptr = chanlist[cname];
1377 log(DEBUG,"add_channel: created: %s",cname);
1378 /* set created to 2 to indicate user
1379 * is the first in the channel
1380 * and should be given ops */
1386 /* channel exists, just fish out a pointer to its struct */
1387 Ptr = FindChan(cname);
1390 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1392 // the override flag allows us to bypass channel modes
1393 // and bans (used by servers)
1394 if ((!override) || (!strcasecmp(user->server,ServerName)))
1396 log(DEBUG,"Not overriding...");
1398 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1399 if (MOD_RESULT == 1) {
1402 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1406 log(DEBUG,"add_channel: checking key, invite, etc");
1407 if (strcmp(Ptr->key,""))
1409 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1412 log(DEBUG,"add_channel: no key given in JOIN");
1413 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1418 log(DEBUG,"key at %p is %s",key,key);
1419 if (strcasecmp(key,Ptr->key))
1421 log(DEBUG,"add_channel: bad key given in JOIN");
1422 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1427 log(DEBUG,"add_channel: no key");
1429 if (Ptr->inviteonly)
1431 log(DEBUG,"add_channel: channel is +i");
1432 if (user->IsInvited(Ptr->name))
1434 /* user was invited to channel */
1435 /* there may be an optional channel NOTICE here */
1439 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1443 log(DEBUG,"add_channel: channel is not +i");
1447 if (usercount(Ptr) == Ptr->limit)
1449 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1454 log(DEBUG,"add_channel: about to walk banlist");
1456 /* check user against the channel banlist */
1459 if (Ptr->bans.size())
1461 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1463 if (match(user->GetFullHost(),i->data))
1465 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1472 log(DEBUG,"add_channel: bans checked");
1477 if ((Ptr) && (user))
1479 user->RemoveInvite(Ptr->name);
1482 log(DEBUG,"add_channel: invites removed");
1487 log(DEBUG,"Overridden checks");
1495 log(DEBUG,"Passed channel checks");
1497 for (int i =0; i != MAXCHANS; i++)
1499 log(DEBUG,"Check location %d",i);
1500 if (user->chans[i].channel == NULL)
1502 log(DEBUG,"Adding into their channel list at location %d",i);
1506 /* first user in is given ops */
1507 user->chans[i].uc_modes = UCMODE_OP;
1511 user->chans[i].uc_modes = 0;
1513 user->chans[i].channel = Ptr;
1514 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1516 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1518 // use the stamdard J token with no privilages.
1519 char buffer[MAXBUF];
1522 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1526 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1528 NetSendToAll(buffer);
1531 log(DEBUG,"Sent JOIN to client");
1535 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1536 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1539 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1540 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1541 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1542 FOREACH_MOD OnUserJoin(user,Ptr);
1546 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1547 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1551 /* remove a channel from a users record, and remove the record from memory
1552 * if the channel has become empty */
1554 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1556 if ((!user) || (!cname))
1558 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1565 if ((!cname) || (!user))
1570 Ptr = FindChan(cname);
1577 FOREACH_MOD OnUserPart(user,Ptr);
1578 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1580 for (int i =0; i != MAXCHANS; i++)
1582 /* zap it from the channel list of the user */
1583 if (user->chans[i].channel == Ptr)
1587 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1591 char buffer[MAXBUF];
1592 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1593 NetSendToAll(buffer);
1602 char buffer[MAXBUF];
1603 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1604 NetSendToAll(buffer);
1607 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1609 user->chans[i].uc_modes = 0;
1610 user->chans[i].channel = NULL;
1611 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1616 /* if there are no users left on the channel */
1617 if (!usercount(Ptr))
1619 chan_hash::iterator iter = chanlist.find(Ptr->name);
1621 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1623 /* kill the record */
1624 if (iter != chanlist.end())
1626 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1627 if (iter->second) delete iter->second;
1628 chanlist.erase(iter);
1634 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1636 if ((!src) || (!user) || (!Ptr) || (!reason))
1638 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1645 if ((!Ptr) || (!user) || (!src))
1650 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1652 if (!has_channel(user,Ptr))
1654 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1659 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1661 if (MOD_RESULT == ACR_DENY)
1664 if (MOD_RESULT == ACR_DEFAULT)
1666 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1668 if (cstatus(src,Ptr) == STATUS_HOP)
1670 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1674 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1681 for (int i =0; i != MAXCHANS; i++)
1683 /* zap it from the channel list of the user */
1684 if (user->chans[i].channel)
1685 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1687 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1688 user->chans[i].uc_modes = 0;
1689 user->chans[i].channel = NULL;
1690 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1695 /* if there are no users left on the channel */
1696 if (!usercount(Ptr))
1698 chan_hash::iterator iter = chanlist.find(Ptr->name);
1700 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1702 /* kill the record */
1703 if (iter != chanlist.end())
1705 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1706 if (iter->second) delete iter->second;
1707 chanlist.erase(iter);
1715 /* This function pokes and hacks at a parameter list like the following:
1717 * PART #winbot,#darkgalaxy :m00!
1719 * to turn it into a series of individual calls like this:
1721 * PART #winbot :m00!
1722 * PART #darkgalaxy :m00!
1724 * The seperate calls are sent to a callback function provided by the caller
1725 * (the caller will usually call itself recursively). The callback function
1726 * must be a command handler. Calling this function on a line with no list causes
1727 * no action to be taken. You must provide a starting and ending parameter number
1728 * where the range of the list can be found, useful if you have a terminating
1729 * parameter as above which is actually not part of the list, or parameters
1730 * before the actual list as well. This code is used by many functions which
1731 * can function as "one to list" (see the RFC) */
1733 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1738 char blog[32][MAXBUF];
1739 char blog2[32][MAXBUF];
1740 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1741 char keystr[MAXBUF];
1744 for (int i = 0; i <32; i++)
1747 for (int i = 0; i <32; i++)
1748 strcpy(blog2[i],"");
1751 for (int i = 0; i <10; i++)
1755 parameters[i] = moo;
1760 if (pcnt > 1) /* we have a key to copy */
1762 strlcpy(keystr,parameters[1],MAXBUF);
1766 if (!parameters[start])
1770 if (!strchr(parameters[start],','))
1775 for (int i = start; i <= end; i++)
1779 strlcat(plist,parameters[i],MAXBUF);
1787 for (int i = 0; i < t; i++)
1789 if (plist[i] == ',')
1792 strlcpy(blog[j++],param,MAXBUF);
1796 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1801 strlcpy(blog[j++],param,MAXBUF);
1804 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1809 if ((joins) && (keystr))
1811 if (strchr(keystr,','))
1815 t2 = strlen(keystr);
1816 for (int i = 0; i < t2; i++)
1818 if (keystr[i] == ',')
1821 strlcpy(blog2[j++],param,MAXBUF);
1825 strlcpy(blog2[j++],param,MAXBUF);
1830 for (j = 0; j < total; j++)
1836 for (q = end; q < pcnt-1; q++)
1838 if (parameters[q+1])
1840 pars[q-end+1] = parameters[q+1];
1843 if ((joins) && (parameters[1]))
1854 /* repeatedly call the function with the hacked parameter list */
1855 if ((joins) && (pcnt > 1))
1859 // pars[1] already set up and containing key from blog2[j]
1864 pars[1] = parameters[1];
1870 fn(pars,pcnt-(end-start),u);
1879 void kill_link(userrec *user,const char* r)
1881 user_hash::iterator iter = clientlist.find(user->nick);
1883 char reason[MAXBUF];
1885 strncpy(reason,r,MAXBUF);
1887 if (strlen(reason)>MAXQUIT)
1889 reason[MAXQUIT-1] = '\0';
1892 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1893 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1894 log(DEBUG,"closing fd %d",user->fd);
1896 /* bugfix, cant close() a nonblocking socket (sux!) */
1897 if (user->registered == 7) {
1898 FOREACH_MOD OnUserQuit(user);
1899 WriteCommonExcept(user,"QUIT :%s",reason);
1901 // Q token must go to ALL servers!!!
1902 char buffer[MAXBUF];
1903 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1904 NetSendToAll(buffer);
1907 /* push the socket on a stack of sockets due to be closed at the next opportunity
1908 * 'Client exited' is an exception to this as it means the client side has already
1909 * closed the socket, we don't need to do it.
1911 fd_reap.push_back(user->fd);
1913 bool do_purge = false;
1915 if (user->registered == 7) {
1916 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1920 if (iter != clientlist.end())
1922 log(DEBUG,"deleting user hash value %d",iter->second);
1923 if ((iter->second) && (user->registered == 7)) {
1924 if (iter->second) delete iter->second;
1926 clientlist.erase(iter);
1929 if (user->registered == 7) {
1930 purge_empty_chans();
1935 void kill_link_silent(userrec *user,const char* r)
1937 user_hash::iterator iter = clientlist.find(user->nick);
1939 char reason[MAXBUF];
1941 strncpy(reason,r,MAXBUF);
1943 if (strlen(reason)>MAXQUIT)
1945 reason[MAXQUIT-1] = '\0';
1948 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1949 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1950 log(DEBUG,"closing fd %d",user->fd);
1952 /* bugfix, cant close() a nonblocking socket (sux!) */
1953 if (user->registered == 7) {
1954 FOREACH_MOD OnUserQuit(user);
1955 WriteCommonExcept(user,"QUIT :%s",reason);
1957 // Q token must go to ALL servers!!!
1958 char buffer[MAXBUF];
1959 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1960 NetSendToAll(buffer);
1963 /* push the socket on a stack of sockets due to be closed at the next opportunity
1964 * 'Client exited' is an exception to this as it means the client side has already
1965 * closed the socket, we don't need to do it.
1967 fd_reap.push_back(user->fd);
1969 bool do_purge = false;
1971 if (iter != clientlist.end())
1973 log(DEBUG,"deleting user hash value %d",iter->second);
1974 if ((iter->second) && (user->registered == 7)) {
1975 if (iter->second) delete iter->second;
1977 clientlist.erase(iter);
1980 if (user->registered == 7) {
1981 purge_empty_chans();
1987 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1989 char* Passwd(userrec *user)
1991 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1993 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2001 bool IsDenied(userrec *user)
2003 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2005 if (match(user->host,i->host) && (i->type == CC_DENY))
2016 /* sends out an error notice to all connected clients (not to be used
2019 void send_error(char *s)
2021 log(DEBUG,"send_error: %s",s);
2022 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2024 if (isnick(i->second->nick))
2026 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2030 // fix - unregistered connections receive ERROR, not NOTICE
2031 Write(i->second->fd,"ERROR :%s",s);
2036 void Error(int status)
2038 signal (SIGALRM, SIG_IGN);
2039 signal (SIGPIPE, SIG_IGN);
2040 signal (SIGTERM, SIG_IGN);
2041 signal (SIGABRT, SIG_IGN);
2042 signal (SIGSEGV, SIG_IGN);
2043 signal (SIGURG, SIG_IGN);
2044 signal (SIGKILL, SIG_IGN);
2045 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2046 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2051 int main(int argc, char **argv)
2055 log(DEBUG,"*** InspIRCd starting up!");
2056 if (!FileExists(CONFIG_FILE))
2058 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2059 log(DEBUG,"main: no config");
2060 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2064 for (int i = 1; i < argc; i++)
2066 if (!strcmp(argv[i],"-nofork")) {
2069 if (!strcmp(argv[i],"-wait")) {
2074 strlcpy(MyExecutable,argv[0],MAXBUF);
2076 if (InspIRCd() == ERROR)
2078 log(DEBUG,"main: daemon function bailed");
2079 printf("ERROR: could not initialise. Shutting down.\n");
2086 template<typename T> inline string ConvToStr(const T &in)
2089 if (!(tmp << in)) return string();
2093 /* re-allocates a nick in the user_hash after they change nicknames,
2094 * returns a pointer to the new user as it may have moved */
2096 userrec* ReHashNick(char* Old, char* New)
2098 user_hash::iterator newnick;
2099 user_hash::iterator oldnick = clientlist.find(Old);
2101 log(DEBUG,"ReHashNick: %s %s",Old,New);
2103 if (!strcasecmp(Old,New))
2105 log(DEBUG,"old nick is new nick, skipping");
2106 return oldnick->second;
2109 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2111 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2113 clientlist[New] = new userrec();
2114 clientlist[New] = oldnick->second;
2115 clientlist.erase(oldnick);
2117 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2119 return clientlist[New];
2122 /* adds or updates an entry in the whowas list */
2123 void AddWhoWas(userrec* u)
2125 user_hash::iterator iter = whowas.find(u->nick);
2126 userrec *a = new userrec();
2127 strlcpy(a->nick,u->nick,NICKMAX);
2128 strlcpy(a->ident,u->ident,64);
2129 strlcpy(a->dhost,u->dhost,256);
2130 strlcpy(a->host,u->host,256);
2131 strlcpy(a->fullname,u->fullname,128);
2132 strlcpy(a->server,u->server,256);
2133 a->signon = u->signon;
2135 /* MAX_WHOWAS: max number of /WHOWAS items
2136 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2137 * can be replaced by a newer one
2140 if (iter == whowas.end())
2142 if (whowas.size() == WHOWAS_MAX)
2144 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2146 // 3600 seconds in an hour ;)
2147 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2149 if (i->second) delete i->second;
2151 log(DEBUG,"added WHOWAS entry, purged an old record");
2158 log(DEBUG,"added fresh WHOWAS entry");
2159 whowas[a->nick] = a;
2164 log(DEBUG,"updated WHOWAS entry");
2165 if (iter->second) delete iter->second;
2171 /* add a client connection to the sockets list */
2172 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2176 char resolved[MAXBUF];
2179 user_hash::iterator iter;
2181 tempnick = ConvToStr(socket) + "-unknown";
2182 sprintf(tn2,"%d-unknown",socket);
2184 iter = clientlist.find(tempnick);
2186 if (iter != clientlist.end()) return;
2189 * It is OK to access the value here this way since we know
2190 * it exists, we just created it above.
2192 * At NO other time should you access a value in a map or a
2193 * hash_map this way.
2195 clientlist[tempnick] = new userrec();
2197 NonBlocking(socket);
2198 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2200 clientlist[tempnick]->fd = socket;
2201 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2202 strncpy(clientlist[tempnick]->host, host,160);
2203 strncpy(clientlist[tempnick]->dhost, host,160);
2204 strncpy(clientlist[tempnick]->server, ServerName,256);
2205 strncpy(clientlist[tempnick]->ident, "unknown",9);
2206 clientlist[tempnick]->registered = 0;
2207 clientlist[tempnick]->signon = time(NULL)+dns_timeout;
2208 clientlist[tempnick]->nping = time(NULL)+240+dns_timeout;
2209 clientlist[tempnick]->lastping = 1;
2210 clientlist[tempnick]->port = port;
2211 strncpy(clientlist[tempnick]->ip,ip,32);
2213 // set the registration timeout for this user
2214 unsigned long class_regtimeout = 90;
2215 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2217 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2219 class_regtimeout = (unsigned long)i->registration_timeout;
2224 int class_flood = 0;
2225 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2227 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2229 class_flood = i->flood;
2234 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2235 clientlist[tempnick]->flood = class_flood;
2237 for (int i = 0; i < MAXCHANS; i++)
2239 clientlist[tempnick]->chans[i].channel = NULL;
2240 clientlist[tempnick]->chans[i].uc_modes = 0;
2243 if (clientlist.size() == MAXCLIENTS)
2244 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2247 char* r = matches_zline(ip);
2248 char* e = matches_exception(ip);
2251 char reason[MAXBUF];
2252 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2253 kill_link(clientlist[tempnick],reason);
2260 return clientlist.size();
2264 int usercount_invisible(void)
2268 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2270 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2275 int usercount_opers(void)
2279 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2281 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2286 int usercount_unknown(void)
2290 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2292 if ((i->second->fd) && (i->second->registered != 7))
2298 long chancount(void)
2300 return chanlist.size();
2303 long count_servs(void)
2306 //for (int j = 0; j < 255; j++)
2308 // if (servers[j] != NULL)
2314 long servercount(void)
2316 return count_servs()+1;
2322 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2324 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2330 void ShowMOTD(userrec *user)
2334 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2337 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2338 for (int i = 0; i != MOTD.size(); i++)
2340 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2342 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2345 void ShowRULES(userrec *user)
2349 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2352 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2353 for (int i = 0; i != RULES.size(); i++)
2355 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2357 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2360 /* shows the message of the day, and any other on-logon stuff */
2361 void FullConnectUser(userrec* user)
2363 user->registered = 7;
2364 user->idle_lastmsg = time(NULL);
2365 log(DEBUG,"ConnectUser: %s",user->nick);
2367 if (strcmp(Passwd(user),"") && (!user->haspassed))
2369 kill_link(user,"Invalid password");
2374 kill_link(user,"Unauthorised connection");
2378 char match_against[MAXBUF];
2379 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2380 char* e = matches_exception(match_against);
2383 char* r = matches_gline(match_against);
2386 char reason[MAXBUF];
2387 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2388 kill_link_silent(user,reason);
2391 r = matches_kline(user->host);
2394 char reason[MAXBUF];
2395 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2396 kill_link_silent(user,reason);
2401 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2402 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2403 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2404 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2405 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2406 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2407 std::stringstream v;
2408 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2409 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2410 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2411 v << std::string(Network);
2412 std::string data005 = v.str();
2413 FOREACH_MOD On005Numeric(data005);
2414 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2415 // so i'd better split it :)
2416 std::stringstream out(data005);
2417 std::string token = "";
2418 std::string line5 = "";
2419 int token_counter = 0;
2423 line5 = line5 + token + " ";
2425 if ((token_counter >= 13) || (out.eof() == true))
2427 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2433 FOREACH_MOD OnUserConnect(user);
2434 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2436 char buffer[MAXBUF];
2437 snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2438 NetSendToAll(buffer);
2441 /* shows the message of the day, and any other on-logon stuff */
2442 void ConnectUser(userrec *user)
2444 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2445 if ((user->dns_done) && (user->registered >= 3))
2447 FullConnectUser(user);
2451 void handle_version(char **parameters, int pcnt, userrec *user)
2453 char Revision[] = "$Revision$";
2455 char *s1 = Revision;
2457 char *v1 = strtok_r(s1," ",&savept);
2459 char *v2 = strtok_r(s1," ",&savept);
2462 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2466 // calls a handler function for a command
2468 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2470 for (int i = 0; i < cmdlist.size(); i++)
2472 if (!strcasecmp(cmdlist[i].command,commandname))
2474 if (cmdlist[i].handler_function)
2476 if (pcnt>=cmdlist[i].min_params)
2478 if (strchr(user->modes,cmdlist[i].flags_needed))
2480 cmdlist[i].handler_function(parameters,pcnt,user);
2488 void DoSplitEveryone()
2490 bool go_again = true;
2494 for (int i = 0; i < 32; i++)
2498 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2500 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2503 j->CloseConnection();
2504 me[i]->connectors.erase(j);
2512 log(DEBUG,"Removed server. Will remove clients...");
2513 // iterate through the userlist and remove all users on this server.
2514 // because we're dealing with a mesh, we dont have to deal with anything
2515 // "down-route" from this server (nice huh)
2517 char reason[MAXBUF];
2521 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2523 if (strcasecmp(u->second->server,ServerName))
2525 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2526 kill_link(u->second,reason);
2536 char islast(const char* s)
2539 for (int j = 0; j < 32; j++)
2543 for (int k = 0; k < me[j]->connectors.size(); k++)
2545 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2549 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2559 long map_count(const char* s)
2562 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2564 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2570 void force_nickchange(userrec* user,const char* newnick)
2577 FOREACH_RESULT(OnUserPreNick(user,newnick));
2579 kill_link(user,"Nickname collision");
2582 if (matches_qline(newnick))
2584 kill_link(user,"Nickname collision");
2592 strncpy(nick,newnick,MAXBUF);
2594 if (user->registered == 7)
2598 handle_nick(pars,1,user);
2604 int process_parameters(char **command_p,char *parameters)
2609 q = strlen(parameters);
2612 /* no parameters, command_p invalid! */
2615 if (parameters[0] == ':')
2617 command_p[0] = parameters+1;
2622 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2624 /* only one parameter */
2625 command_p[0] = parameters;
2626 if (parameters[0] == ':')
2628 if (strchr(parameters,' ') != NULL)
2636 command_p[j++] = parameters;
2637 for (int i = 0; i <= q; i++)
2639 if (parameters[i] == ' ')
2641 command_p[j++] = parameters+i+1;
2642 parameters[i] = '\0';
2643 if (command_p[j-1][0] == ':')
2645 *command_p[j-1]++; /* remove dodgy ":" */
2647 /* parameter like this marks end of the sequence */
2651 return j; /* returns total number of items in the list */
2654 void process_command(userrec *user, char* cmd)
2658 char *command_p[127];
2659 char p[MAXBUF], temp[MAXBUF];
2660 int i, j, items, cmd_found;
2662 for (int i = 0; i < 127; i++)
2663 command_p[i] = NULL;
2673 if (!strcmp(cmd,""))
2678 int total_params = 0;
2681 for (int q = 0; q < strlen(cmd)-1; q++)
2683 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2686 // found a 'trailing', we dont count them after this.
2694 // another phidjit bug...
2695 if (total_params > 126)
2697 //kill_link(user,"Protocol violation (1)");
2698 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2702 strlcpy(temp,cmd,MAXBUF);
2704 std::string tmp = cmd;
2705 for (int i = 0; i <= MODCOUNT; i++)
2707 std::string oldtmp = tmp;
2708 modules[i]->OnServerRaw(tmp,true,user);
2711 log(DEBUG,"A Module changed the input string!");
2712 log(DEBUG,"New string: %s",tmp.c_str());
2713 log(DEBUG,"Old string: %s",oldtmp.c_str());
2717 strlcpy(cmd,tmp.c_str(),MAXBUF);
2718 strlcpy(temp,cmd,MAXBUF);
2720 if (!strchr(cmd,' '))
2722 /* no parameters, lets skip the formalities and not chop up
2724 log(DEBUG,"About to preprocess command with no params");
2726 command_p[0] = NULL;
2728 for (int i = 0; i <= strlen(cmd); i++)
2730 cmd[i] = toupper(cmd[i]);
2732 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2739 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2740 for (int i = 0; i < strlen(temp); i++)
2742 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2748 /* split the full string into a command plus parameters */
2752 if (strchr(cmd,' '))
2754 for (int i = 0; i <= strlen(cmd); i++)
2756 /* capitalise the command ONLY, leave params intact */
2757 cmd[i] = toupper(cmd[i]);
2758 /* are we nearly there yet?! :P */
2762 parameters = cmd+i+1;
2770 for (int i = 0; i <= strlen(cmd); i++)
2772 cmd[i] = toupper(cmd[i]);
2779 if (strlen(command)>MAXCOMMAND)
2781 //kill_link(user,"Protocol violation (2)");
2782 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2786 for (int x = 0; x < strlen(command); x++)
2788 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2790 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2792 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2794 //kill_link(user,"Protocol violation (3)");
2795 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2802 for (int i = 0; i != cmdlist.size(); i++)
2804 if (strcmp(cmdlist[i].command,""))
2806 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2808 log(DEBUG,"Found matching command");
2812 if (strcmp(parameters,""))
2814 items = process_parameters(command_p,parameters);
2819 command_p[0] = NULL;
2825 command_p[0] = NULL;
2830 log(DEBUG,"Processing command");
2832 /* activity resets the ping pending timer */
2833 user->nping = time(NULL) + 120;
2834 if ((items) < cmdlist[i].min_params)
2836 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2837 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2840 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2842 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2843 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2847 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2849 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2850 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2854 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2856 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2858 if ((!isnick(user->nick)) || (user->registered != 7))
2860 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2861 WriteServ(user->fd,"451 %s :You have not registered",command);
2865 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2867 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2868 if (cmdlist[i].handler_function)
2870 /* ikky /stats counters */
2875 user->bytes_in += strlen(temp);
2877 user->bytes_out+=strlen(temp);
2880 cmdlist[i].use_count++;
2881 cmdlist[i].total_bytes+=strlen(temp);
2884 /* WARNING: nothing may come after the
2885 * command handler call, as the handler
2886 * may free the user structure! */
2888 cmdlist[i].handler_function(command_p,items,user);
2894 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2895 WriteServ(user->fd,"451 %s :You have not registered",command);
2903 if ((!cmd_found) && (user))
2905 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2906 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2911 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2914 /* create the command and push it onto the table */
2915 strlcpy(comm.command,cmd,MAXBUF);
2916 comm.handler_function = f;
2917 comm.flags_needed = flags;
2918 comm.min_params = minparams;
2920 comm.total_bytes = 0;
2921 cmdlist.push_back(comm);
2922 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2925 void SetupCommandTable(void)
2927 createcommand("USER",handle_user,0,4);
2928 createcommand("NICK",handle_nick,0,1);
2929 createcommand("QUIT",handle_quit,0,0);
2930 createcommand("VERSION",handle_version,0,0);
2931 createcommand("PING",handle_ping,0,1);
2932 createcommand("PONG",handle_pong,0,1);
2933 createcommand("ADMIN",handle_admin,0,0);
2934 createcommand("PRIVMSG",handle_privmsg,0,2);
2935 createcommand("INFO",handle_info,0,0);
2936 createcommand("TIME",handle_time,0,0);
2937 createcommand("WHOIS",handle_whois,0,1);
2938 createcommand("WALLOPS",handle_wallops,'o',1);
2939 createcommand("NOTICE",handle_notice,0,2);
2940 createcommand("JOIN",handle_join,0,1);
2941 createcommand("NAMES",handle_names,0,1);
2942 createcommand("PART",handle_part,0,1);
2943 createcommand("KICK",handle_kick,0,2);
2944 createcommand("MODE",handle_mode,0,1);
2945 createcommand("TOPIC",handle_topic,0,1);
2946 createcommand("WHO",handle_who,0,1);
2947 createcommand("MOTD",handle_motd,0,0);
2948 createcommand("RULES",handle_rules,0,0);
2949 createcommand("OPER",handle_oper,0,2);
2950 createcommand("LIST",handle_list,0,0);
2951 createcommand("DIE",handle_die,'o',1);
2952 createcommand("RESTART",handle_restart,'o',1);
2953 createcommand("KILL",handle_kill,'o',2);
2954 createcommand("REHASH",handle_rehash,'o',0);
2955 createcommand("LUSERS",handle_lusers,0,0);
2956 createcommand("STATS",handle_stats,0,1);
2957 createcommand("USERHOST",handle_userhost,0,1);
2958 createcommand("AWAY",handle_away,0,0);
2959 createcommand("ISON",handle_ison,0,0);
2960 createcommand("SUMMON",handle_summon,0,0);
2961 createcommand("USERS",handle_users,0,0);
2962 createcommand("INVITE",handle_invite,0,2);
2963 createcommand("PASS",handle_pass,0,1);
2964 createcommand("TRACE",handle_trace,'o',0);
2965 createcommand("WHOWAS",handle_whowas,0,1);
2966 createcommand("CONNECT",handle_connect,'o',1);
2967 createcommand("SQUIT",handle_squit,'o',0);
2968 createcommand("MODULES",handle_modules,'o',0);
2969 createcommand("LINKS",handle_links,0,0);
2970 createcommand("MAP",handle_map,0,0);
2971 createcommand("KLINE",handle_kline,'o',1);
2972 createcommand("GLINE",handle_gline,'o',1);
2973 createcommand("ZLINE",handle_zline,'o',1);
2974 createcommand("QLINE",handle_qline,'o',1);
2975 createcommand("ELINE",handle_eline,'o',1);
2976 createcommand("SERVER",handle_server,0,0);
2979 void process_buffer(const char* cmdbuf,userrec *user)
2983 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2990 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2993 if (!strcmp(cmdbuf,""))
2997 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2999 strlcpy(cmd,cmdbuf,MAXBUF);
3000 if (!strcmp(cmd,""))
3004 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3006 cmd[strlen(cmd)-1] = '\0';
3008 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3010 cmd[strlen(cmd)-1] = '\0';
3013 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3015 cmd[strlen(cmd)-1] = '\0';
3018 if (!strcmp(cmd,""))
3022 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3024 if ((user) && (cmd))
3026 process_command(user,cmd);
3030 void DoSync(serverrec* serv, char* tcp_host)
3033 log(DEBUG,"Sending sync");
3034 // send start of sync marker: Y <timestamp>
3035 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3036 // except the ones its receiving it from.
3037 snprintf(data,MAXBUF,"Y %d",time(NULL));
3038 serv->SendPacket(data,tcp_host);
3039 // send users and channels
3040 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3042 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
3043 serv->SendPacket(data,tcp_host);
3044 if (strchr(u->second->modes,'o'))
3046 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3047 serv->SendPacket(data,tcp_host);
3049 for (int i = 0; i <= MODCOUNT; i++)
3051 string_list l = modules[i]->OnUserSync(u->second);
3052 for (int j = 0; j < l.size(); j++)
3054 strlcpy(data,l[j].c_str(),MAXBUF);
3055 serv->SendPacket(data,tcp_host);
3058 if (strcmp(chlist(u->second),""))
3060 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3061 serv->SendPacket(data,tcp_host);
3064 // send channel modes, topics etc...
3065 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3067 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3068 serv->SendPacket(data,tcp_host);
3069 for (int i = 0; i <= MODCOUNT; i++)
3071 string_list l = modules[i]->OnChannelSync(c->second);
3072 for (int j = 0; j < l.size(); j++)
3074 strlcpy(data,l[j].c_str(),MAXBUF);
3075 serv->SendPacket(data,tcp_host);
3078 if (strcmp(c->second->topic,""))
3080 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3081 serv->SendPacket(data,tcp_host);
3083 // send current banlist
3085 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3087 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3088 serv->SendPacket(data,tcp_host);
3091 // sync global zlines, glines, etc
3092 sync_xlines(serv,tcp_host);
3094 for (int j = 0; j < 32; j++)
3098 for (int k = 0; k < me[j]->connectors.size(); k++)
3100 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3102 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3103 serv->SendPacket(data,tcp_host);
3104 NetSendMyRoutingTable();
3110 snprintf(data,MAXBUF,"F %d",time(NULL));
3111 serv->SendPacket(data,tcp_host);
3112 log(DEBUG,"Sent sync");
3113 // ircd sends its serverlist after the end of sync here
3117 void NetSendMyRoutingTable()
3119 // send out a line saying what is reachable to us.
3120 // E.g. if A is linked to B C and D, send out:
3122 // if its only linked to B and D send out:
3124 // if it has no links, dont even send out the line at all.
3125 char buffer[MAXBUF];
3126 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3127 bool sendit = false;
3128 for (int i = 0; i < 32; i++)
3132 for (int j = 0; j < me[i]->connectors.size(); j++)
3134 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3136 strlcat(buffer," ",MAXBUF);
3137 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3144 NetSendToAll(buffer);
3148 void DoSplit(const char* params)
3150 bool go_again = true;
3154 for (int i = 0; i < 32; i++)
3158 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3160 if (!strcasecmp(j->GetServerName().c_str(),params))
3163 j->CloseConnection();
3164 me[i]->connectors.erase(j);
3172 log(DEBUG,"Removed server. Will remove clients...");
3173 // iterate through the userlist and remove all users on this server.
3174 // because we're dealing with a mesh, we dont have to deal with anything
3175 // "down-route" from this server (nice huh)
3177 char reason[MAXBUF];
3178 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3182 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3184 if (!strcasecmp(u->second->server,params))
3186 kill_link(u->second,reason);
3194 // removes a server. Will NOT remove its users!
3196 void RemoveServer(const char* name)
3198 bool go_again = true;
3202 for (int i = 0; i < 32; i++)
3206 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3208 if (!strcasecmp(j->GetServerName().c_str(),name))
3211 j->CloseConnection();
3212 me[i]->connectors.erase(j);
3223 int reap_counter = 0;
3227 struct sockaddr_in client,server;
3228 char addrs[MAXBUF][255];
3229 int incomingSockfd, result = TRUE;
3232 int selectResult = 0, selectResult2 = 0;
3233 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3234 char resolvedHost[MAXBUF];
3238 log_file = fopen("ircd.log","a+");
3241 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3245 log(DEBUG,"InspIRCd: startup: begin");
3249 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3251 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3253 SetupCommandTable();
3254 log(DEBUG,"InspIRCd: startup: default command table set up");
3256 ReadConfig(true,NULL);
3257 if (strcmp(DieValue,""))
3259 printf("WARNING: %s\n\n",DieValue);
3260 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3263 log(DEBUG,"InspIRCd: startup: read config");
3265 int count2 = 0, count3 = 0;
3267 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3269 ConfValue("bind","port",count,configToken,&config_f);
3270 ConfValue("bind","address",count,Addr,&config_f);
3271 ConfValue("bind","type",count,Type,&config_f);
3272 if (!strcmp(Type,"servers"))
3274 char Default[MAXBUF];
3275 strcpy(Default,"no");
3276 ConfValue("bind","default",count,Default,&config_f);
3277 if (strchr(Default,'y'))
3279 defaultRoute = count3;
3280 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3282 me[count3] = new serverrec(ServerName,100L,false);
3283 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3285 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3294 ports[count2] = atoi(configToken);
3295 strlcpy(addrs[count2],Addr,256);
3298 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3301 UDPportCount = count3;
3303 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3305 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3309 /* BugFix By Craig! :p */
3311 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3313 char modfile[MAXBUF];
3314 ConfValue("module","name",count2,configToken,&config_f);
3315 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3316 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3317 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3318 /* If The File Doesnt exist, Trying to load it
3319 * Will Segfault the IRCd.. So, check to see if
3320 * it Exists, Before Proceeding. */
3321 if (FileExists(modfile))
3323 factory[count] = new ircd_module(modfile);
3324 if (factory[count]->LastError())
3326 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3327 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3330 if (factory[count]->factory)
3332 modules[count] = factory[count]->factory->CreateModule();
3333 /* save the module and the module's classfactory, if
3334 * this isnt done, random crashes can occur :/ */
3335 module_names.push_back(modfile);
3339 log(DEBUG,"Unable to load %s",modfile);
3340 printf("Unable to load %s\nExiting...\n",modfile);
3343 /* Increase the Count */
3348 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3349 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3352 MODCOUNT = count - 1;
3353 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3355 printf("\nInspIRCd is now running!\n");
3357 startup_time = time(NULL);
3361 log(VERBOSE,"Not forking as -nofork was specified");
3365 if (DaemonSeed() == ERROR)
3367 log(DEBUG,"InspIRCd: startup: can't daemonise");
3368 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3374 ConfValue("pid","file",0,PID,&config_f);
3378 /* setup select call */
3379 FD_ZERO(&selectFds);
3380 log(DEBUG,"InspIRCd: startup: zero selects");
3381 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3383 for (count = 0; count < portCount; count++)
3385 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3387 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3390 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3392 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3394 else /* well we at least bound to one socket so we'll continue */
3400 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3402 /* if we didn't bind to anything then abort */
3403 if (boundPortCount == 0)
3405 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3410 length = sizeof (client);
3411 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3413 /* main loop, this never returns */
3416 #ifdef _POSIX_PRIORITY_SCHEDULING
3426 user_hash::iterator count2 = clientlist.begin();
3428 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3429 // them in a list, then reap the list every second or so.
3430 if ((reap_counter % 50) == 0)
3432 // These functions eat cpu, and should not be done so often!
3434 // update the status of klines, etc
3436 #ifdef _POSIX_PRIORITY_SCHEDULING
3440 if (reap_counter>300)
3442 if (fd_reap.size() > 0)
3444 for( int n = 0; n < fd_reap.size(); n++)
3446 //Blocking(fd_reap[n]);
3448 shutdown (fd_reap[n],2);
3449 //NonBlocking(fd_reap[n]);
3458 FD_ZERO(&serverfds);
3461 for (int x = 0; x != UDPportCount; x++)
3464 FD_SET(me[x]->fd, &serverfds);
3470 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3473 for (int x = 0; x != UDPportCount; x++)
3475 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3477 char remotehost[MAXBUF],resolved[MAXBUF];
3478 length = sizeof (client);
3479 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3480 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3481 if(CleanAndResolve(resolved, remotehost) != TRUE)
3483 strlcpy(resolved,remotehost,MAXBUF);
3485 // add to this connections ircd_connector vector
3486 // *FIX* - we need the LOCAL port not the remote port in &client!
3487 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3492 for (int x = 0; x < UDPportCount; x++)
3494 std::deque<std::string> msgs;
3496 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3498 for (int ctr = 0; ctr < msgs.size(); ctr++)
3500 char udp_msg[MAXBUF];
3501 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3502 if (strlen(udp_msg)<1)
3504 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3507 // during a netburst, send all data to all other linked servers
3508 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3510 if (is_uline(tcp_host))
3512 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3514 NetSendToAllExcept(tcp_host,udp_msg);
3518 NetSendToAllExcept(tcp_host,udp_msg);
3520 FOREACH_MOD OnPacketReceive(udp_msg);
3521 handle_link_packet(udp_msg, tcp_host, me[x]);
3528 while (count2 != clientlist.end())
3531 tval.tv_usec = 5000;
3534 int total_in_this_set = 0;
3536 user_hash::iterator xcount = count2;
3537 user_hash::iterator endingiter = count2;
3539 if (count2 == clientlist.end()) break;
3542 if (count2->second->fd != 0)
3544 // assemble up to 64 sockets into an fd_set
3545 // to implement a pooling mechanism.
3547 // This should be up to 64x faster than the
3548 // old implementation.
3549 while (total_in_this_set < 64)
3551 if (count2 != clientlist.end())
3553 // we don't check the state of remote users.
3554 if (count2->second->fd > 0)
3556 FD_SET (count2->second->fd, &sfd);
3558 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3559 // their connection class.
3560 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3562 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3563 kill_link(count2->second,"Registration timeout");
3566 if ((time(NULL) > count2->second->signon) && (count2->second->registered == 3))
3568 count2->second->dns_done = true;
3569 FullConnectUser(count2->second);
3572 if ((count2->second->dns_done) && (count2->second->registered == 3)) // both NICK and USER... and DNS
3574 FullConnectUser(count2->second);
3577 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3579 if ((!count2->second->lastping) && (count2->second->registered == 7))
3581 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3582 kill_link(count2->second,"Ping timeout");
3585 Write(count2->second->fd,"PING :%s",ServerName);
3586 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3587 count2->second->lastping = 0;
3588 count2->second->nping = time(NULL)+120;
3592 total_in_this_set++;
3597 endingiter = count2;
3598 count2 = xcount; // roll back to where we were
3602 tval.tv_usec = 5000;
3604 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3606 // now loop through all of the items in this pool if any are waiting
3607 //if (selectResult2 > 0)
3608 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3611 #ifdef _POSIX_PRIORITY_SCHEDULING
3616 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3618 memset(data, 0, 10240);
3619 result = read(count2a->second->fd, data, 10240);
3623 userrec* current = count2a->second;
3624 int currfd = current->fd;
3625 char* l = strtok(data,"\n");
3630 if ((floodlines > current->flood) && (current->flood != 0))
3632 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3633 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3634 kill_link(current,"Excess flood");
3637 char sanitized[NetBufferSize];
3638 memset(sanitized, 0, NetBufferSize);
3640 for (int pt = 0; pt < strlen(l); pt++)
3644 sanitized[ptt++] = l[pt];
3647 sanitized[ptt] = '\0';
3648 if (strlen(sanitized))
3652 // we're gonna re-scan to check if the nick is gone, after every
3653 // command - if it has, we're gonna bail
3654 bool find_again = false;
3655 process_buffer(sanitized,current);
3657 // look for the user's record in case it's changed
3658 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3660 if (c2->second->fd == currfd)
3662 // found again, update pointer
3663 current == c2->second;
3672 l = strtok(NULL,"\n");
3677 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3679 log(DEBUG,"killing: %s",count2a->second->nick);
3680 kill_link(count2a->second,strerror(errno));
3684 // result EAGAIN means nothing read
3685 if (result == EAGAIN)
3693 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3694 kill_link(count2a->second,"Client exited");
3695 // must bail here? kill_link removes the hash, corrupting the iterator
3696 log(DEBUG,"Bailing from client exit");
3700 else if (result > 0)
3705 for (int q = 0; q < total_in_this_set; q++)
3707 // there is no iterator += operator :(
3708 //if (count2 != clientlist.end())
3715 // set up select call
3716 for (count = 0; count < boundPortCount; count++)
3718 FD_SET (openSockfd[count], &selectFds);
3722 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3724 /* select is reporting a waiting socket. Poll them all to find out which */
3725 if (selectResult > 0)
3727 char target[MAXBUF], resolved[MAXBUF];
3728 for (count = 0; count < boundPortCount; count++)
3730 if (FD_ISSET (openSockfd[count], &selectFds))
3732 length = sizeof (client);
3733 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3735 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3736 strlcpy (resolved, target, MAXBUF);
3738 if (incomingSockfd < 0)
3740 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3741 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3745 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3746 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3753 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3756 close (incomingSockfd);