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"
61 #define nspace __gnu_cxx
66 int LogLevel = DEFAULT;
67 char ServerName[MAXBUF];
69 char ServerDesc[MAXBUF];
70 char AdminName[MAXBUF];
71 char AdminEmail[MAXBUF];
72 char AdminNick[MAXBUF];
74 char restartpass[MAXBUF];
78 char PrefixQuit[MAXBUF];
79 char DieValue[MAXBUF];
81 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
82 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
84 time_t startup_time = time(NULL);
85 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
86 extern int MaxWhoResults;
89 bool AllowHalfop = true;
90 bool AllowProtect = true;
91 bool AllowFounder = true;
93 extern std::vector<Module*> modules;
94 std::vector<std::string> module_names;
95 extern std::vector<ircd_module*> factory;
96 std::vector<int> fd_reap;
105 template<> struct hash<in_addr>
107 template<> struct nspace::hash<in_addr>
110 size_t operator()(const struct in_addr &a) const
113 memcpy(&q,&a,sizeof(size_t));
118 template<> struct hash<string>
120 template<> struct nspace::hash<string>
123 size_t operator()(const string &s) const
126 static struct hash<const char *> strhash;
127 strlcpy(a,s.c_str(),MAXBUF);
138 bool operator()(const string& s1, const string& s2) const
140 char a[MAXBUF],b[MAXBUF];
141 strlcpy(a,s1.c_str(),MAXBUF);
142 strlcpy(b,s2.c_str(),MAXBUF);
143 return (strcasecmp(a,b) == 0);
148 struct InAddr_HashComp
151 bool operator()(const in_addr &s1, const in_addr &s2) const
156 memcpy(&q,&s1,sizeof(size_t));
157 memcpy(&p,&s2,sizeof(size_t));
165 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
166 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
167 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
168 typedef std::deque<command_t> command_table;
174 user_hash clientlist;
177 command_table cmdlist;
184 struct linger linger = { 0 };
185 char MyExecutable[1024];
186 int boundPortCount = 0;
187 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
188 int defaultRoute = 0;
192 long MyKey = C.GenKey();
196 int has_channel(userrec *u, chanrec *c);
197 int usercount(chanrec *c);
198 int usercount_i(chanrec *c);
199 void update_stats_l(int fd,int data_out);
200 char* Passwd(userrec *user);
201 bool IsDenied(userrec *user);
202 void AddWhoWas(userrec* u);
204 std::vector<long> auth_cookies;
205 std::stringstream config_f(stringstream::in | stringstream::out);
211 char Revision[] = "$Revision$";
214 char *v1 = strtok_r(s1," ",&savept);
216 char *v2 = strtok_r(s1," ",&savept);
218 return (long)(atof(v2)*10000);
222 std::string getservername()
227 std::string getserverdesc()
232 std::string getnetworkname()
237 std::string getadminname()
242 std::string getadminemail()
247 std::string getadminnick()
252 void log(int level,char *text, ...)
254 char textbuffer[MAXBUF];
257 struct tm * timeinfo;
258 if (level < LogLevel)
262 timeinfo = localtime (&rawtime);
267 va_start (argsPtr, text);
268 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
270 strlcpy(b,asctime(timeinfo),MAXBUF);
271 b[strlen(b)-1] = ':';
272 fprintf(log_file,"%s %s\n",b,textbuffer);
275 // nofork enabled? display it on terminal too
276 printf("%s %s\n",b,textbuffer);
281 void readfile(file_cache &F, const char* fname)
284 char linebuf[MAXBUF];
286 log(DEBUG,"readfile: loading %s",fname);
288 file = fopen(fname,"r");
293 fgets(linebuf,sizeof(linebuf),file);
294 linebuf[strlen(linebuf)-1]='\0';
295 if (!strcmp(linebuf,""))
301 F.push_back(linebuf);
308 log(DEBUG,"readfile: failed to load file: %s",fname);
310 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
313 void ReadConfig(bool bail, userrec* user)
315 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
316 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF];
318 std::stringstream errstr;
320 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
325 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
333 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
334 while (!errstr.eof())
336 errstr.getline(dataline,1024);
337 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
342 WriteOpers("There were errors in the configuration file:",user->nick);
343 while (!errstr.eof())
345 errstr.getline(dataline,1024);
346 WriteOpers(dataline);
353 ConfValue("server","name",0,ServerName,&config_f);
354 ConfValue("server","description",0,ServerDesc,&config_f);
355 ConfValue("server","network",0,Network,&config_f);
356 ConfValue("admin","name",0,AdminName,&config_f);
357 ConfValue("admin","email",0,AdminEmail,&config_f);
358 ConfValue("admin","nick",0,AdminNick,&config_f);
359 ConfValue("files","motd",0,motd,&config_f);
360 ConfValue("files","rules",0,rules,&config_f);
361 ConfValue("power","diepass",0,diepass,&config_f);
362 ConfValue("power","pause",0,pauseval,&config_f);
363 ConfValue("power","restartpass",0,restartpass,&config_f);
364 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
365 ConfValue("die","value",0,DieValue,&config_f);
366 ConfValue("options","loglevel",0,dbg,&config_f);
367 ConfValue("options","netbuffersize",0,NB,&config_f);
368 ConfValue("options","maxwho",0,MW,&config_f);
369 ConfValue("options","allowhalfop",0,AH,&config_f);
370 ConfValue("options","allowprotect",0,AP,&config_f);
371 ConfValue("options","allowfounder",0,AF,&config_f);
372 NetBufferSize = atoi(NB);
373 MaxWhoResults = atoi(MW);
374 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
375 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
376 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
377 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
379 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
380 NetBufferSize = 10240;
382 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
384 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
387 if (!strcmp(dbg,"debug"))
389 if (!strcmp(dbg,"verbose"))
391 if (!strcmp(dbg,"default"))
393 if (!strcmp(dbg,"sparse"))
395 if (!strcmp(dbg,"none"))
398 log(DEFAULT,"Reading message of the day...");
399 readfile(RULES,rules);
400 log(DEFAULT,"Reading connect classes...");
402 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
405 ConfValue("connect","allow",i,Value,&config_f);
406 ConfValue("connect","timeout",i,timeout,&config_f);
407 ConfValue("connect","flood",i,flood,&config_f);
408 if (strcmp(Value,""))
410 strlcpy(c.host,Value,MAXBUF);
412 strlcpy(Value,"",MAXBUF);
413 ConfValue("connect","password",i,Value,&config_f);
414 strlcpy(c.pass,Value,MAXBUF);
415 c.registration_timeout = 90; // default is 2 minutes
416 c.flood = atoi(flood);
419 c.registration_timeout = atoi(timeout);
421 Classes.push_back(c);
422 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
426 ConfValue("connect","deny",i,Value,&config_f);
427 strlcpy(c.host,Value,MAXBUF);
429 Classes.push_back(c);
430 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
434 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
435 read_xline_defaults();
436 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
438 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
441 /* write formatted text to a socket, in same format as printf */
443 void Write(int sock,char *text, ...)
447 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
450 char textbuffer[MAXBUF];
454 va_start (argsPtr, text);
455 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
457 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
461 write(sock,tb,strlen(tb));
462 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
466 /* write a server formatted numeric response to a single socket */
468 void WriteServ(int sock, char* text, ...)
472 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
475 char textbuffer[MAXBUF],tb[MAXBUF];
477 va_start (argsPtr, text);
479 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
481 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
485 write(sock,tb,strlen(tb));
486 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
490 /* write text from an originating user to originating user */
492 void WriteFrom(int sock, userrec *user,char* text, ...)
494 if ((!text) || (!user))
496 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
499 char textbuffer[MAXBUF],tb[MAXBUF];
501 va_start (argsPtr, text);
503 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
505 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
509 write(sock,tb,strlen(tb));
510 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
514 /* write text to an destination user from a source user (e.g. user privmsg) */
516 void WriteTo(userrec *source, userrec *dest,char *data, ...)
518 if ((!dest) || (!data))
520 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
523 char textbuffer[MAXBUF],tb[MAXBUF];
525 va_start (argsPtr, data);
526 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
530 // if no source given send it from the server.
533 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
537 WriteFrom(dest->fd,source,"%s",textbuffer);
541 /* write formatted text from a source user to all users on a channel
542 * including the sender (NOT for privmsg, notice etc!) */
544 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
546 if ((!Ptr) || (!user) || (!text))
548 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
551 char textbuffer[MAXBUF];
553 va_start (argsPtr, text);
554 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
556 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
558 if (has_channel(i->second,Ptr))
560 WriteTo(user,i->second,"%s",textbuffer);
565 /* write formatted text from a source user to all users on a channel
566 * including the sender (NOT for privmsg, notice etc!) doesnt send to
567 * users on remote servers */
569 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
571 if ((!Ptr) || (!text))
573 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
576 char textbuffer[MAXBUF];
578 va_start (argsPtr, text);
579 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
581 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
583 if (has_channel(i->second,Ptr))
585 if (i->second->fd != -1)
589 WriteServ(i->second->fd,"%s",textbuffer);
593 WriteTo(user,i->second,"%s",textbuffer);
601 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
603 if ((!Ptr) || (!user) || (!text))
605 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
608 char textbuffer[MAXBUF];
610 va_start (argsPtr, text);
611 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
613 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
617 if (has_channel(i->second,Ptr))
619 WriteServ(i->second->fd,"%s",textbuffer);
626 /* write formatted text from a source user to all users on a channel except
627 * for the sender (for privmsg etc) */
629 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
631 if ((!Ptr) || (!user) || (!text))
633 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
636 char textbuffer[MAXBUF];
638 va_start (argsPtr, text);
639 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
642 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
646 if (has_channel(i->second,Ptr) && (user != i->second))
648 WriteTo(user,i->second,"%s",textbuffer);
655 std::string GetServerDescription(char* servername)
657 for (int j = 0; j < 32; j++)
661 for (int k = 0; k < me[j]->connectors.size(); k++)
663 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
665 return me[j]->connectors[k].GetDescription();
669 return ServerDesc; // not a remote server that can be found, it must be me.
674 /* write a formatted string to all users who share at least one common
675 * channel, including the source user e.g. for use in NICK */
677 void WriteCommon(userrec *u, char* text, ...)
681 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
685 if (u->registered != 7) {
686 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
690 char textbuffer[MAXBUF];
692 va_start (argsPtr, text);
693 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
696 WriteFrom(u->fd,u,"%s",textbuffer);
698 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
702 if (common_channels(u,i->second) && (i->second != u))
704 WriteFrom(i->second->fd,u,"%s",textbuffer);
710 /* write a formatted string to all users who share at least one common
711 * channel, NOT including the source user e.g. for use in QUIT */
713 void WriteCommonExcept(userrec *u, char* text, ...)
717 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
721 if (u->registered != 7) {
722 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
726 char textbuffer[MAXBUF];
728 va_start (argsPtr, text);
729 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
732 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
736 if ((common_channels(u,i->second)) && (u != i->second))
738 WriteFrom(i->second->fd,u,"%s",textbuffer);
744 void WriteOpers(char* text, ...)
748 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
752 char textbuffer[MAXBUF];
754 va_start (argsPtr, text);
755 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
758 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
762 if (strchr(i->second->modes,'o'))
764 if (strchr(i->second->modes,'s'))
766 // send server notices to all with +s
767 // (TODO: needs SNOMASKs)
768 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
775 // returns TRUE of any users on channel C occupy server 'servername'.
777 bool ChanAnyOnThisServer(chanrec *c,char* servername)
779 log(DEBUG,"ChanAnyOnThisServer");
780 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
782 if (has_channel(i->second,c))
784 if (!strcasecmp(i->second->server,servername))
793 // returns true if user 'u' shares any common channels with any users on server 'servername'
795 bool CommonOnThisServer(userrec* u,const char* servername)
797 log(DEBUG,"ChanAnyOnThisServer");
798 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
800 if ((common_channels(u,i->second)) && (u != i->second))
802 if (!strcasecmp(i->second->server,servername))
804 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
813 void NetSendToCommon(userrec* u, char* s)
816 snprintf(buffer,MAXBUF,"%s",s);
818 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
820 for (int j = 0; j < 32; j++)
824 for (int k = 0; k < me[j]->connectors.size(); k++)
826 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
828 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
836 void NetSendToAll(char* s)
839 snprintf(buffer,MAXBUF,"%s",s);
841 log(DEBUG,"NetSendToAll: '%s'",s);
843 for (int j = 0; j < 32; j++)
847 for (int k = 0; k < me[j]->connectors.size(); k++)
849 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
855 void NetSendToAllAlive(char* s)
858 snprintf(buffer,MAXBUF,"%s",s);
860 log(DEBUG,"NetSendToAllAlive: '%s'",s);
862 for (int j = 0; j < 32; j++)
866 for (int k = 0; k < me[j]->connectors.size(); k++)
868 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
870 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
874 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
882 void NetSendToOne(char* target,char* s)
885 snprintf(buffer,MAXBUF,"%s",s);
887 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
889 for (int j = 0; j < 32; j++)
893 for (int k = 0; k < me[j]->connectors.size(); k++)
895 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
897 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
904 void NetSendToAllExcept(const char* target,char* s)
907 snprintf(buffer,MAXBUF,"%s",s);
909 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
911 for (int j = 0; j < 32; j++)
915 for (int k = 0; k < me[j]->connectors.size(); k++)
917 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
919 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
927 void WriteMode(const char* modes, int flags, const char* text, ...)
929 if ((!text) || (!modes) || (!flags))
931 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
935 char textbuffer[MAXBUF];
937 va_start (argsPtr, text);
938 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
941 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
945 bool send_to_user = false;
950 for (int n = 0; n < strlen(modes); n++)
952 if (!hasumode(i->second,modes[n]))
954 send_to_user = false;
959 else if (flags == WM_OR)
961 send_to_user = false;
962 for (int n = 0; n < strlen(modes); n++)
964 if (hasumode(i->second,modes[n]))
974 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
981 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
983 if ((!text) || (!source))
985 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
990 char textbuffer[MAXBUF];
992 va_start (argsPtr, text);
993 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
996 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1000 if (strchr(i->second->modes,'w'))
1002 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1009 char buffer[MAXBUF];
1010 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1011 NetSendToAll(buffer);
1015 /* convert a string to lowercase. Note following special circumstances
1016 * taken from RFC 1459. Many "official" server branches still hold to this
1017 * rule so i will too;
1019 * Because of IRC's scandanavian origin, the characters {}| are
1020 * considered to be the lower case equivalents of the characters []\,
1021 * respectively. This is a critical issue when determining the
1022 * equivalence of two nicknames.
1025 void strlower(char *n)
1031 for (int i = 0; i != strlen(n); i++)
1033 n[i] = tolower(n[i]);
1045 /* Find a user record by nickname and return a pointer to it */
1047 userrec* Find(string nick)
1049 user_hash::iterator iter = clientlist.find(nick);
1051 if (iter == clientlist.end())
1052 /* Couldn't find it */
1055 return iter->second;
1058 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1060 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1064 if (i->second->fd == fd)
1066 i->second->bytes_out+=data_out;
1067 i->second->cmds_out++;
1074 /* find a channel record by channel name and return a pointer to it */
1076 chanrec* FindChan(const char* chan)
1080 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1084 chan_hash::iterator iter = chanlist.find(chan);
1086 if (iter == chanlist.end())
1087 /* Couldn't find it */
1090 return iter->second;
1094 void purge_empty_chans(void)
1096 int go_again = 1, purge = 0;
1101 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1104 if (!usercount(i->second))
1106 /* kill the record */
1107 if (i != chanlist.end())
1109 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1119 log(DEBUG,"skipped purge for %s",i->second->name);
1124 log(DEBUG,"completed channel purge, killed %d",purge);
1128 char scratch[MAXBUF];
1129 char sparam[MAXBUF];
1131 char* chanmodes(chanrec *chan)
1135 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1142 if (chan->noexternal)
1144 strlcat(scratch,"n",MAXMODES);
1146 if (chan->topiclock)
1148 strlcat(scratch,"t",MAXMODES);
1150 if (strcmp(chan->key,""))
1152 strlcat(scratch,"k",MAXMODES);
1156 strlcat(scratch,"l",MAXMODES);
1158 if (chan->inviteonly)
1160 strlcat(scratch,"i",MAXMODES);
1162 if (chan->moderated)
1164 strlcat(scratch,"m",MAXMODES);
1168 strlcat(scratch,"s",MAXMODES);
1170 if (chan->c_private)
1172 strlcat(scratch,"p",MAXMODES);
1174 if (strcmp(chan->key,""))
1176 strlcat(sparam," ",MAXBUF);
1177 strlcat(sparam,chan->key,MAXBUF);
1182 sprintf(foo," %d",chan->limit);
1183 strlcat(sparam,foo,MAXBUF);
1185 if (strlen(chan->custom_modes))
1187 strlcat(scratch,chan->custom_modes,MAXMODES);
1188 for (int z = 0; z < strlen(chan->custom_modes); z++)
1190 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1193 strlcat(sparam," ",MAXBUF);
1194 strlcat(sparam,extparam.c_str(),MAXBUF);
1198 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1199 strlcat(scratch,sparam,MAXMODES);
1204 /* compile a userlist of a channel into a string, each nick seperated by
1205 * spaces and op, voice etc status shown as @ and + */
1207 void userlist(userrec *user,chanrec *c)
1209 if ((!c) || (!user))
1211 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1215 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1216 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1218 if (has_channel(i->second,c))
1220 if (isnick(i->second->nick))
1222 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1224 /* user is +i, and source not on the channel, does not show
1225 * nick in NAMES list */
1228 strlcat(list,cmode(i->second,c),MAXBUF);
1229 strlcat(list,i->second->nick,MAXBUF);
1230 strlcat(list," ",MAXBUF);
1231 if (strlen(list)>(480-NICKMAX))
1233 /* list overflowed into
1234 * multiple numerics */
1235 WriteServ(user->fd,list);
1236 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1241 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1243 WriteServ(user->fd,list);
1247 /* return a count of the users on a specific channel accounting for
1248 * invisible users who won't increase the count. e.g. for /LIST */
1250 int usercount_i(chanrec *c)
1257 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1262 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1266 if (has_channel(i->second,c))
1268 if (isnick(i->second->nick))
1270 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1272 /* user is +i, and source not on the channel, does not show
1273 * nick in NAMES list */
1281 log(DEBUG,"usercount_i: %s %d",c->name,count);
1286 int usercount(chanrec *c)
1293 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1298 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1302 if (has_channel(i->second,c))
1304 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1311 log(DEBUG,"usercount: %s %d",c->name,count);
1316 /* add a channel to a user, creating the record for it if needed and linking
1317 * it to the user record */
1319 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1321 if ((!user) || (!cn))
1323 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1332 strncpy(cname,cn,MAXBUF);
1334 // we MUST declare this wherever we use FOREACH_RESULT
1337 if (strlen(cname) > CHANMAX-1)
1339 cname[CHANMAX-1] = '\0';
1342 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1344 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1346 return NULL; // already on the channel!
1350 if (!FindChan(cname))
1353 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1354 if (MOD_RESULT == 1) {
1358 /* create a new one */
1359 log(DEBUG,"add_channel: creating: %s",cname);
1361 chanlist[cname] = new chanrec();
1363 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1364 chanlist[cname]->topiclock = 1;
1365 chanlist[cname]->noexternal = 1;
1366 chanlist[cname]->created = time(NULL);
1367 strcpy(chanlist[cname]->topic, "");
1368 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1369 chanlist[cname]->topicset = 0;
1370 Ptr = chanlist[cname];
1371 log(DEBUG,"add_channel: created: %s",cname);
1372 /* set created to 2 to indicate user
1373 * is the first in the channel
1374 * and should be given ops */
1380 /* channel exists, just fish out a pointer to its struct */
1381 Ptr = FindChan(cname);
1384 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1386 // the override flag allows us to bypass channel modes
1387 // and bans (used by servers)
1391 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1392 if (MOD_RESULT == 1) {
1396 if (MOD_RESULT == 0)
1399 if (strcmp(Ptr->key,""))
1401 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1404 log(DEBUG,"add_channel: no key given in JOIN");
1405 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1410 log(DEBUG,"key at %p is %s",key,key);
1411 if (strcasecmp(key,Ptr->key))
1413 log(DEBUG,"add_channel: bad key given in JOIN");
1414 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1419 log(DEBUG,"add_channel: no key");
1421 if (Ptr->inviteonly)
1423 log(DEBUG,"add_channel: channel is +i");
1424 if (user->IsInvited(Ptr->name))
1426 /* user was invited to channel */
1427 /* there may be an optional channel NOTICE here */
1431 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1435 log(DEBUG,"add_channel: channel is not +i");
1439 if (usercount(Ptr) == Ptr->limit)
1441 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1446 log(DEBUG,"add_channel: about to walk banlist");
1448 /* check user against the channel banlist */
1451 if (Ptr->bans.size())
1453 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1455 if (match(user->GetFullHost(),i->data))
1457 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1464 log(DEBUG,"add_channel: bans checked");
1469 if ((Ptr) && (user))
1471 user->RemoveInvite(Ptr->name);
1474 log(DEBUG,"add_channel: invites removed");
1479 log(DEBUG,"Overridden checks");
1487 log(DEBUG,"Passed channel checks");
1489 for (int i =0; i != MAXCHANS; i++)
1491 log(DEBUG,"Check location %d",i);
1492 if (user->chans[i].channel == NULL)
1494 log(DEBUG,"Adding into their channel list at location %d",i);
1498 /* first user in is given ops */
1499 user->chans[i].uc_modes = UCMODE_OP;
1503 user->chans[i].uc_modes = 0;
1505 user->chans[i].channel = Ptr;
1506 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1508 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1510 // use the stamdard J token with no privilages.
1511 char buffer[MAXBUF];
1514 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1518 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1520 NetSendToAll(buffer);
1523 log(DEBUG,"Sent JOIN to client");
1527 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1528 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1531 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1532 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1533 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1534 FOREACH_MOD OnUserJoin(user,Ptr);
1538 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1539 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1543 /* remove a channel from a users record, and remove the record from memory
1544 * if the channel has become empty */
1546 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1548 if ((!user) || (!cname))
1550 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1557 if ((!cname) || (!user))
1562 Ptr = FindChan(cname);
1569 FOREACH_MOD OnUserPart(user,Ptr);
1570 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1572 for (int i =0; i != MAXCHANS; i++)
1574 /* zap it from the channel list of the user */
1575 if (user->chans[i].channel == Ptr)
1579 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1583 char buffer[MAXBUF];
1584 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1585 NetSendToAll(buffer);
1594 char buffer[MAXBUF];
1595 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1596 NetSendToAll(buffer);
1599 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1601 user->chans[i].uc_modes = 0;
1602 user->chans[i].channel = NULL;
1603 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1608 /* if there are no users left on the channel */
1609 if (!usercount(Ptr))
1611 chan_hash::iterator iter = chanlist.find(Ptr->name);
1613 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1615 /* kill the record */
1616 if (iter != chanlist.end())
1618 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1619 delete iter->second;
1620 chanlist.erase(iter);
1626 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1628 if ((!src) || (!user) || (!Ptr) || (!reason))
1630 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1637 if ((!Ptr) || (!user) || (!src))
1642 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1644 if (!has_channel(user,Ptr))
1646 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1651 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1653 if (MOD_RESULT == ACR_DENY)
1656 if (MOD_RESULT == ACR_DEFAULT)
1658 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1660 if (cstatus(src,Ptr) == STATUS_HOP)
1662 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1666 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1673 for (int i =0; i != MAXCHANS; i++)
1675 /* zap it from the channel list of the user */
1676 if (user->chans[i].channel)
1677 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1679 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1680 user->chans[i].uc_modes = 0;
1681 user->chans[i].channel = NULL;
1682 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1687 /* if there are no users left on the channel */
1688 if (!usercount(Ptr))
1690 chan_hash::iterator iter = chanlist.find(Ptr->name);
1692 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1694 /* kill the record */
1695 if (iter != chanlist.end())
1697 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1698 delete iter->second;
1699 chanlist.erase(iter);
1707 /* This function pokes and hacks at a parameter list like the following:
1709 * PART #winbot, #darkgalaxy :m00!
1711 * to turn it into a series of individual calls like this:
1713 * PART #winbot :m00!
1714 * PART #darkgalaxy :m00!
1716 * The seperate calls are sent to a callback function provided by the caller
1717 * (the caller will usually call itself recursively). The callback function
1718 * must be a command handler. Calling this function on a line with no list causes
1719 * no action to be taken. You must provide a starting and ending parameter number
1720 * where the range of the list can be found, useful if you have a terminating
1721 * parameter as above which is actually not part of the list, or parameters
1722 * before the actual list as well. This code is used by many functions which
1723 * can function as "one to list" (see the RFC) */
1725 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1730 char blog[32][MAXBUF];
1731 char blog2[32][MAXBUF];
1732 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1733 char keystr[MAXBUF];
1736 for (int i = 0; i <32; i++)
1739 for (int i = 0; i <32; i++)
1740 strcpy(blog2[i],"");
1743 for (int i = 0; i <10; i++)
1747 parameters[i] = moo;
1752 if (pcnt > 1) /* we have a key to copy */
1754 strlcpy(keystr,parameters[1],MAXBUF);
1758 if (!parameters[start])
1762 if (!strchr(parameters[start],','))
1767 for (int i = start; i <= end; i++)
1771 strlcat(plist,parameters[i],MAXBUF);
1779 for (int i = 0; i < t; i++)
1781 if (plist[i] == ',')
1784 strlcpy(blog[j++],param,MAXBUF);
1788 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1793 strlcpy(blog[j++],param,MAXBUF);
1796 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1801 if ((joins) && (keystr))
1803 if (strchr(keystr,','))
1807 t2 = strlen(keystr);
1808 for (int i = 0; i < t2; i++)
1810 if (keystr[i] == ',')
1813 strlcpy(blog2[j++],param,MAXBUF);
1817 strlcpy(blog2[j++],param,MAXBUF);
1822 for (j = 0; j < total; j++)
1828 for (q = end; q < pcnt-1; q++)
1830 if (parameters[q+1])
1832 pars[q-end+1] = parameters[q+1];
1835 if ((joins) && (parameters[1]))
1846 /* repeatedly call the function with the hacked parameter list */
1847 if ((joins) && (pcnt > 1))
1851 // pars[1] already set up and containing key from blog2[j]
1856 pars[1] = parameters[1];
1862 fn(pars,pcnt-(end-start),u);
1871 void kill_link(userrec *user,const char* r)
1873 user_hash::iterator iter = clientlist.find(user->nick);
1875 char reason[MAXBUF];
1877 strncpy(reason,r,MAXBUF);
1879 if (strlen(reason)>MAXQUIT)
1881 reason[MAXQUIT-1] = '\0';
1884 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1885 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1886 log(DEBUG,"closing fd %d",user->fd);
1888 /* bugfix, cant close() a nonblocking socket (sux!) */
1889 if (user->registered == 7) {
1890 FOREACH_MOD OnUserQuit(user);
1891 WriteCommonExcept(user,"QUIT :%s",reason);
1893 // Q token must go to ALL servers!!!
1894 char buffer[MAXBUF];
1895 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1896 NetSendToAll(buffer);
1899 /* push the socket on a stack of sockets due to be closed at the next opportunity
1900 * 'Client exited' is an exception to this as it means the client side has already
1901 * closed the socket, we don't need to do it.
1903 fd_reap.push_back(user->fd);
1905 bool do_purge = false;
1907 if (user->registered == 7) {
1908 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1912 if (iter != clientlist.end())
1914 log(DEBUG,"deleting user hash value %d",iter->second);
1915 if ((iter->second) && (user->registered == 7)) {
1916 delete iter->second;
1918 clientlist.erase(iter);
1921 if (user->registered == 7) {
1922 purge_empty_chans();
1926 void kill_link_silent(userrec *user,const char* r)
1928 user_hash::iterator iter = clientlist.find(user->nick);
1930 char reason[MAXBUF];
1932 strncpy(reason,r,MAXBUF);
1934 if (strlen(reason)>MAXQUIT)
1936 reason[MAXQUIT-1] = '\0';
1939 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1940 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1941 log(DEBUG,"closing fd %d",user->fd);
1943 /* bugfix, cant close() a nonblocking socket (sux!) */
1944 if (user->registered == 7) {
1945 FOREACH_MOD OnUserQuit(user);
1946 WriteCommonExcept(user,"QUIT :%s",reason);
1948 // Q token must go to ALL servers!!!
1949 char buffer[MAXBUF];
1950 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1951 NetSendToAll(buffer);
1954 /* push the socket on a stack of sockets due to be closed at the next opportunity
1955 * 'Client exited' is an exception to this as it means the client side has already
1956 * closed the socket, we don't need to do it.
1958 fd_reap.push_back(user->fd);
1960 bool do_purge = false;
1962 if (iter != clientlist.end())
1964 log(DEBUG,"deleting user hash value %d",iter->second);
1965 if ((iter->second) && (user->registered == 7)) {
1966 delete iter->second;
1968 clientlist.erase(iter);
1971 if (user->registered == 7) {
1972 purge_empty_chans();
1978 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1980 char* Passwd(userrec *user)
1982 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1984 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1992 bool IsDenied(userrec *user)
1994 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1996 if (match(user->host,i->host) && (i->type == CC_DENY))
2007 /* sends out an error notice to all connected clients (not to be used
2010 void send_error(char *s)
2012 log(DEBUG,"send_error: %s",s);
2013 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2015 if (isnick(i->second->nick))
2017 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2021 // fix - unregistered connections receive ERROR, not NOTICE
2022 Write(i->second->fd,"ERROR :%s",s);
2027 void Error(int status)
2029 signal (SIGALRM, SIG_IGN);
2030 signal (SIGPIPE, SIG_IGN);
2031 signal (SIGTERM, SIG_IGN);
2032 signal (SIGABRT, SIG_IGN);
2033 signal (SIGSEGV, SIG_IGN);
2034 signal (SIGURG, SIG_IGN);
2035 signal (SIGKILL, SIG_IGN);
2036 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2037 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2042 int main(int argc, char **argv)
2046 log(DEBUG,"*** InspIRCd starting up!");
2047 if (!FileExists(CONFIG_FILE))
2049 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2050 log(DEBUG,"main: no config");
2051 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2055 for (int i = 1; i < argc; i++)
2057 if (!strcmp(argv[i],"-nofork")) {
2060 if (!strcmp(argv[i],"-wait")) {
2065 strlcpy(MyExecutable,argv[0],MAXBUF);
2067 if (InspIRCd() == ERROR)
2069 log(DEBUG,"main: daemon function bailed");
2070 printf("ERROR: could not initialise. Shutting down.\n");
2077 template<typename T> inline string ConvToStr(const T &in)
2080 if (!(tmp << in)) return string();
2084 /* re-allocates a nick in the user_hash after they change nicknames,
2085 * returns a pointer to the new user as it may have moved */
2087 userrec* ReHashNick(char* Old, char* New)
2089 user_hash::iterator newnick;
2090 user_hash::iterator oldnick = clientlist.find(Old);
2092 log(DEBUG,"ReHashNick: %s %s",Old,New);
2094 if (!strcasecmp(Old,New))
2096 log(DEBUG,"old nick is new nick, skipping");
2097 return oldnick->second;
2100 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2102 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2104 clientlist[New] = new userrec();
2105 clientlist[New] = oldnick->second;
2106 /*delete oldnick->second; */
2107 clientlist.erase(oldnick);
2109 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2111 return clientlist[New];
2114 /* adds or updates an entry in the whowas list */
2115 void AddWhoWas(userrec* u)
2117 user_hash::iterator iter = whowas.find(u->nick);
2118 userrec *a = new userrec();
2119 strlcpy(a->nick,u->nick,NICKMAX);
2120 strlcpy(a->ident,u->ident,64);
2121 strlcpy(a->dhost,u->dhost,256);
2122 strlcpy(a->host,u->host,256);
2123 strlcpy(a->fullname,u->fullname,128);
2124 strlcpy(a->server,u->server,256);
2125 a->signon = u->signon;
2127 /* MAX_WHOWAS: max number of /WHOWAS items
2128 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2129 * can be replaced by a newer one
2132 if (iter == whowas.end())
2134 if (whowas.size() == WHOWAS_MAX)
2136 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2138 // 3600 seconds in an hour ;)
2139 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2143 log(DEBUG,"added WHOWAS entry, purged an old record");
2150 log(DEBUG,"added fresh WHOWAS entry");
2151 whowas[a->nick] = a;
2156 log(DEBUG,"updated WHOWAS entry");
2157 delete iter->second;
2163 /* add a client connection to the sockets list */
2164 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2168 char resolved[MAXBUF];
2171 user_hash::iterator iter;
2173 tempnick = ConvToStr(socket) + "-unknown";
2174 sprintf(tn2,"%d-unknown",socket);
2176 iter = clientlist.find(tempnick);
2178 if (iter != clientlist.end()) return;
2181 * It is OK to access the value here this way since we know
2182 * it exists, we just created it above.
2184 * At NO other time should you access a value in a map or a
2185 * hash_map this way.
2187 clientlist[tempnick] = new userrec();
2189 NonBlocking(socket);
2190 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2192 clientlist[tempnick]->fd = socket;
2193 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2194 strncpy(clientlist[tempnick]->host, host,160);
2195 strncpy(clientlist[tempnick]->dhost, host,160);
2196 strncpy(clientlist[tempnick]->server, ServerName,256);
2197 strncpy(clientlist[tempnick]->ident, "unknown",9);
2198 clientlist[tempnick]->registered = 0;
2199 clientlist[tempnick]->signon = time(NULL);
2200 clientlist[tempnick]->nping = time(NULL)+240;
2201 clientlist[tempnick]->lastping = 1;
2202 clientlist[tempnick]->port = port;
2203 strncpy(clientlist[tempnick]->ip,ip,32);
2207 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2211 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2214 // set the registration timeout for this user
2215 unsigned long class_regtimeout = 90;
2216 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2218 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2220 class_regtimeout = (unsigned long)i->registration_timeout;
2225 int class_flood = 0;
2226 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2228 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2230 class_flood = i->flood;
2235 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2236 clientlist[tempnick]->flood = class_flood;
2238 for (int i = 0; i < MAXCHANS; i++)
2240 clientlist[tempnick]->chans[i].channel = NULL;
2241 clientlist[tempnick]->chans[i].uc_modes = 0;
2244 if (clientlist.size() == MAXCLIENTS)
2245 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2247 char* r = matches_zline(ip);
2250 char reason[MAXBUF];
2251 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2252 kill_link(clientlist[tempnick],reason);
2259 return clientlist.size();
2263 int usercount_invisible(void)
2267 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2269 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2274 int usercount_opers(void)
2278 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2280 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2285 int usercount_unknown(void)
2289 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2291 if ((i->second->fd) && (i->second->registered != 7))
2297 long chancount(void)
2299 return chanlist.size();
2302 long count_servs(void)
2305 //for (int j = 0; j < 255; j++)
2307 // if (servers[j] != NULL)
2313 long servercount(void)
2315 return count_servs()+1;
2321 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2323 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2329 void ShowMOTD(userrec *user)
2333 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2336 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2337 for (int i = 0; i != MOTD.size(); i++)
2339 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2341 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2344 void ShowRULES(userrec *user)
2348 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2351 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2352 for (int i = 0; i != RULES.size(); i++)
2354 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2356 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2359 /* shows the message of the day, and any other on-logon stuff */
2360 void ConnectUser(userrec *user)
2362 user->registered = 7;
2363 user->idle_lastmsg = time(NULL);
2364 log(DEBUG,"ConnectUser: %s",user->nick);
2366 if (strcmp(Passwd(user),"") && (!user->haspassed))
2368 kill_link(user,"Invalid password");
2373 kill_link(user,"Unauthorised connection");
2377 char match_against[MAXBUF];
2378 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2379 char* r = matches_gline(match_against);
2382 char reason[MAXBUF];
2383 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2384 kill_link_silent(user,reason);
2388 r = matches_kline(user->host);
2391 char reason[MAXBUF];
2392 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2393 kill_link_silent(user,reason);
2397 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2398 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2399 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2400 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2401 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2402 std::string data005 = "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+MAP SAFELIST MAXCHANNELS=20 MAXBANS=60 NICKLEN=30 TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=" + std::string(Network);
2403 FOREACH_MOD On005Numeric(data005);
2404 WriteServ(user->fd,"005 %s %s :are supported by this server",user->nick,data005.c_str());
2406 FOREACH_MOD OnUserConnect(user);
2407 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2409 char buffer[MAXBUF];
2410 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);
2411 NetSendToAll(buffer);
2414 void handle_version(char **parameters, int pcnt, userrec *user)
2416 char Revision[] = "$Revision$";
2418 char *s1 = Revision;
2420 char *v1 = strtok_r(s1," ",&savept);
2422 char *v2 = strtok_r(s1," ",&savept);
2425 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2429 // calls a handler function for a command
2431 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2433 for (int i = 0; i < cmdlist.size(); i++)
2435 if (!strcasecmp(cmdlist[i].command,commandname))
2437 if (cmdlist[i].handler_function)
2439 if (pcnt>=cmdlist[i].min_params)
2441 if (strchr(user->modes,cmdlist[i].flags_needed))
2443 cmdlist[i].handler_function(parameters,pcnt,user);
2451 void DoSplitEveryone()
2453 bool go_again = true;
2457 for (int i = 0; i < 32; i++)
2461 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2463 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2466 j->CloseConnection();
2467 me[i]->connectors.erase(j);
2475 log(DEBUG,"Removed server. Will remove clients...");
2476 // iterate through the userlist and remove all users on this server.
2477 // because we're dealing with a mesh, we dont have to deal with anything
2478 // "down-route" from this server (nice huh)
2480 char reason[MAXBUF];
2484 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2486 if (strcasecmp(u->second->server,ServerName))
2488 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2489 kill_link(u->second,reason);
2499 char islast(const char* s)
2502 for (int j = 0; j < 32; j++)
2506 for (int k = 0; k < me[j]->connectors.size(); k++)
2508 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2512 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2522 long map_count(const char* s)
2525 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2527 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2533 void force_nickchange(userrec* user,const char* newnick)
2540 FOREACH_RESULT(OnUserPreNick(user,newnick));
2542 kill_link(user,"Nickname collision");
2545 if (matches_qline(newnick))
2547 kill_link(user,"Nickname collision");
2555 strncpy(nick,newnick,MAXBUF);
2557 if (user->registered == 7)
2561 handle_nick(pars,1,user);
2567 int process_parameters(char **command_p,char *parameters)
2572 q = strlen(parameters);
2575 /* no parameters, command_p invalid! */
2578 if (parameters[0] == ':')
2580 command_p[0] = parameters+1;
2585 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2587 /* only one parameter */
2588 command_p[0] = parameters;
2589 if (parameters[0] == ':')
2591 if (strchr(parameters,' ') != NULL)
2599 command_p[j++] = parameters;
2600 for (int i = 0; i <= q; i++)
2602 if (parameters[i] == ' ')
2604 command_p[j++] = parameters+i+1;
2605 parameters[i] = '\0';
2606 if (command_p[j-1][0] == ':')
2608 *command_p[j-1]++; /* remove dodgy ":" */
2610 /* parameter like this marks end of the sequence */
2614 return j; /* returns total number of items in the list */
2617 void process_command(userrec *user, char* cmd)
2621 char *command_p[127];
2622 char p[MAXBUF], temp[MAXBUF];
2623 int i, j, items, cmd_found;
2625 for (int i = 0; i < 127; i++)
2626 command_p[i] = NULL;
2636 if (!strcmp(cmd,""))
2641 int total_params = 0;
2644 for (int q = 0; q < strlen(cmd)-1; q++)
2646 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2649 // found a 'trailing', we dont count them after this.
2657 // another phidjit bug...
2658 if (total_params > 126)
2660 //kill_link(user,"Protocol violation (1)");
2661 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2665 strlcpy(temp,cmd,MAXBUF);
2667 std::string tmp = cmd;
2668 for (int i = 0; i <= MODCOUNT; i++)
2670 std::string oldtmp = tmp;
2671 modules[i]->OnServerRaw(tmp,true,user);
2674 log(DEBUG,"A Module changed the input string!");
2675 log(DEBUG,"New string: %s",tmp.c_str());
2676 log(DEBUG,"Old string: %s",oldtmp.c_str());
2680 strlcpy(cmd,tmp.c_str(),MAXBUF);
2681 strlcpy(temp,cmd,MAXBUF);
2683 if (!strchr(cmd,' '))
2685 /* no parameters, lets skip the formalities and not chop up
2687 log(DEBUG,"About to preprocess command with no params");
2689 command_p[0] = NULL;
2691 for (int i = 0; i <= strlen(cmd); i++)
2693 cmd[i] = toupper(cmd[i]);
2695 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2702 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2703 for (int i = 0; i < strlen(temp); i++)
2705 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2711 /* split the full string into a command plus parameters */
2715 if (strchr(cmd,' '))
2717 for (int i = 0; i <= strlen(cmd); i++)
2719 /* capitalise the command ONLY, leave params intact */
2720 cmd[i] = toupper(cmd[i]);
2721 /* are we nearly there yet?! :P */
2725 parameters = cmd+i+1;
2733 for (int i = 0; i <= strlen(cmd); i++)
2735 cmd[i] = toupper(cmd[i]);
2742 if (strlen(command)>MAXCOMMAND)
2744 //kill_link(user,"Protocol violation (2)");
2745 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2749 for (int x = 0; x < strlen(command); x++)
2751 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2753 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2755 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2757 //kill_link(user,"Protocol violation (3)");
2758 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2765 for (int i = 0; i != cmdlist.size(); i++)
2767 if (strcmp(cmdlist[i].command,""))
2769 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2771 log(DEBUG,"Found matching command");
2775 if (strcmp(parameters,""))
2777 items = process_parameters(command_p,parameters);
2782 command_p[0] = NULL;
2788 command_p[0] = NULL;
2793 log(DEBUG,"Processing command");
2795 /* activity resets the ping pending timer */
2796 user->nping = time(NULL) + 120;
2797 if ((items) < cmdlist[i].min_params)
2799 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2800 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2803 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2805 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2806 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2810 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2812 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2813 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2817 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2819 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2821 if ((!isnick(user->nick)) || (user->registered != 7))
2823 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2824 WriteServ(user->fd,"451 %s :You have not registered",command);
2828 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2830 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2831 if (cmdlist[i].handler_function)
2833 /* ikky /stats counters */
2838 user->bytes_in += strlen(temp);
2841 cmdlist[i].use_count++;
2842 cmdlist[i].total_bytes+=strlen(temp);
2845 /* WARNING: nothing may come after the
2846 * command handler call, as the handler
2847 * may free the user structure! */
2849 cmdlist[i].handler_function(command_p,items,user);
2855 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2856 WriteServ(user->fd,"451 %s :You have not registered",command);
2864 if ((!cmd_found) && (user))
2866 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2867 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2872 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2875 /* create the command and push it onto the table */
2876 strlcpy(comm.command,cmd,MAXBUF);
2877 comm.handler_function = f;
2878 comm.flags_needed = flags;
2879 comm.min_params = minparams;
2881 comm.total_bytes = 0;
2882 cmdlist.push_back(comm);
2883 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2886 void SetupCommandTable(void)
2888 createcommand("USER",handle_user,0,4);
2889 createcommand("NICK",handle_nick,0,1);
2890 createcommand("QUIT",handle_quit,0,0);
2891 createcommand("VERSION",handle_version,0,0);
2892 createcommand("PING",handle_ping,0,1);
2893 createcommand("PONG",handle_pong,0,1);
2894 createcommand("ADMIN",handle_admin,0,0);
2895 createcommand("PRIVMSG",handle_privmsg,0,2);
2896 createcommand("INFO",handle_info,0,0);
2897 createcommand("TIME",handle_time,0,0);
2898 createcommand("WHOIS",handle_whois,0,1);
2899 createcommand("WALLOPS",handle_wallops,'o',1);
2900 createcommand("NOTICE",handle_notice,0,2);
2901 createcommand("JOIN",handle_join,0,1);
2902 createcommand("NAMES",handle_names,0,1);
2903 createcommand("PART",handle_part,0,1);
2904 createcommand("KICK",handle_kick,0,2);
2905 createcommand("MODE",handle_mode,0,1);
2906 createcommand("TOPIC",handle_topic,0,1);
2907 createcommand("WHO",handle_who,0,1);
2908 createcommand("MOTD",handle_motd,0,0);
2909 createcommand("RULES",handle_rules,0,0);
2910 createcommand("OPER",handle_oper,0,2);
2911 createcommand("LIST",handle_list,0,0);
2912 createcommand("DIE",handle_die,'o',1);
2913 createcommand("RESTART",handle_restart,'o',1);
2914 createcommand("KILL",handle_kill,'o',2);
2915 createcommand("REHASH",handle_rehash,'o',0);
2916 createcommand("LUSERS",handle_lusers,0,0);
2917 createcommand("STATS",handle_stats,0,1);
2918 createcommand("USERHOST",handle_userhost,0,1);
2919 createcommand("AWAY",handle_away,0,0);
2920 createcommand("ISON",handle_ison,0,0);
2921 createcommand("SUMMON",handle_summon,0,0);
2922 createcommand("USERS",handle_users,0,0);
2923 createcommand("INVITE",handle_invite,0,2);
2924 createcommand("PASS",handle_pass,0,1);
2925 createcommand("TRACE",handle_trace,'o',0);
2926 createcommand("WHOWAS",handle_whowas,0,1);
2927 createcommand("CONNECT",handle_connect,'o',1);
2928 createcommand("SQUIT",handle_squit,'o',0);
2929 createcommand("MODULES",handle_modules,'o',0);
2930 createcommand("LINKS",handle_links,0,0);
2931 createcommand("MAP",handle_map,0,0);
2932 createcommand("KLINE",handle_kline,'o',1);
2933 createcommand("GLINE",handle_gline,'o',1);
2934 createcommand("ZLINE",handle_zline,'o',1);
2935 createcommand("QLINE",handle_qline,'o',1);
2936 createcommand("SERVER",handle_server,0,0);
2939 void process_buffer(const char* cmdbuf,userrec *user)
2943 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2950 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2953 if (!strcmp(cmdbuf,""))
2957 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2959 strlcpy(cmd,cmdbuf,MAXBUF);
2960 if (!strcmp(cmd,""))
2964 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2966 cmd[strlen(cmd)-1] = '\0';
2968 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2970 cmd[strlen(cmd)-1] = '\0';
2973 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2975 cmd[strlen(cmd)-1] = '\0';
2978 if (!strcmp(cmd,""))
2982 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2984 if ((user) && (cmd))
2986 process_command(user,cmd);
2990 void DoSync(serverrec* serv, char* tcp_host)
2993 log(DEBUG,"Sending sync");
2994 // send start of sync marker: Y <timestamp>
2995 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2996 // except the ones its receiving it from.
2997 snprintf(data,MAXBUF,"Y %d",time(NULL));
2998 serv->SendPacket(data,tcp_host);
2999 // send users and channels
3000 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3002 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);
3003 serv->SendPacket(data,tcp_host);
3004 if (strchr(u->second->modes,'o'))
3006 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3007 serv->SendPacket(data,tcp_host);
3009 for (int i = 0; i <= MODCOUNT; i++)
3011 string_list l = modules[i]->OnUserSync(u->second);
3012 for (int j = 0; j < l.size(); j++)
3014 strlcpy(data,l[j].c_str(),MAXBUF);
3015 serv->SendPacket(data,tcp_host);
3018 if (strcmp(chlist(u->second),""))
3020 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3021 serv->SendPacket(data,tcp_host);
3024 // send channel modes, topics etc...
3025 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3027 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3028 serv->SendPacket(data,tcp_host);
3029 for (int i = 0; i <= MODCOUNT; i++)
3031 string_list l = modules[i]->OnChannelSync(c->second);
3032 for (int j = 0; j < l.size(); j++)
3034 strlcpy(data,l[j].c_str(),MAXBUF);
3035 serv->SendPacket(data,tcp_host);
3038 if (strcmp(c->second->topic,""))
3040 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3041 serv->SendPacket(data,tcp_host);
3043 // send current banlist
3045 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3047 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3048 serv->SendPacket(data,tcp_host);
3051 // sync global zlines, glines, etc
3052 sync_xlines(serv,tcp_host);
3054 for (int j = 0; j < 32; j++)
3058 for (int k = 0; k < me[j]->connectors.size(); k++)
3060 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3062 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3063 serv->SendPacket(data,tcp_host);
3064 NetSendMyRoutingTable();
3070 snprintf(data,MAXBUF,"F %d",time(NULL));
3071 serv->SendPacket(data,tcp_host);
3072 log(DEBUG,"Sent sync");
3073 // ircd sends its serverlist after the end of sync here
3077 void NetSendMyRoutingTable()
3079 // send out a line saying what is reachable to us.
3080 // E.g. if A is linked to B C and D, send out:
3082 // if its only linked to B and D send out:
3084 // if it has no links, dont even send out the line at all.
3085 char buffer[MAXBUF];
3086 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3087 bool sendit = false;
3088 for (int i = 0; i < 32; i++)
3092 for (int j = 0; j < me[i]->connectors.size(); j++)
3094 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3096 strlcat(buffer," ",MAXBUF);
3097 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3104 NetSendToAll(buffer);
3108 void DoSplit(const char* params)
3110 bool go_again = true;
3114 for (int i = 0; i < 32; i++)
3118 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3120 if (!strcasecmp(j->GetServerName().c_str(),params))
3123 j->CloseConnection();
3124 me[i]->connectors.erase(j);
3132 log(DEBUG,"Removed server. Will remove clients...");
3133 // iterate through the userlist and remove all users on this server.
3134 // because we're dealing with a mesh, we dont have to deal with anything
3135 // "down-route" from this server (nice huh)
3137 char reason[MAXBUF];
3138 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3142 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3144 if (!strcasecmp(u->second->server,params))
3146 kill_link(u->second,reason);
3154 // removes a server. Will NOT remove its users!
3156 void RemoveServer(const char* name)
3158 bool go_again = true;
3162 for (int i = 0; i < 32; i++)
3166 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3168 if (!strcasecmp(j->GetServerName().c_str(),name))
3171 j->CloseConnection();
3172 me[i]->connectors.erase(j);
3183 int reap_counter = 0;
3187 struct sockaddr_in client,server;
3188 char addrs[MAXBUF][255];
3189 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3192 int selectResult = 0, selectResult2 = 0;
3193 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3194 char resolvedHost[MAXBUF];
3198 log_file = fopen("ircd.log","a+");
3201 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3205 log(DEBUG,"InspIRCd: startup: begin");
3209 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3211 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3213 SetupCommandTable();
3214 log(DEBUG,"InspIRCd: startup: default command table set up");
3216 ReadConfig(true,NULL);
3217 if (strcmp(DieValue,""))
3219 printf("WARNING: %s\n\n",DieValue);
3222 log(DEBUG,"InspIRCd: startup: read config");
3224 int count2 = 0, count3 = 0;
3226 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3228 ConfValue("bind","port",count,configToken,&config_f);
3229 ConfValue("bind","address",count,Addr,&config_f);
3230 ConfValue("bind","type",count,Type,&config_f);
3231 if (!strcmp(Type,"servers"))
3233 char Default[MAXBUF];
3234 strcpy(Default,"no");
3235 ConfValue("bind","default",count,Default,&config_f);
3236 if (strchr(Default,'y'))
3238 defaultRoute = count3;
3239 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3241 me[count3] = new serverrec(ServerName,100L,false);
3242 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3244 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3253 ports[count2] = atoi(configToken);
3254 strlcpy(addrs[count2],Addr,256);
3257 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3260 UDPportCount = count3;
3262 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3264 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3268 /* BugFix By Craig! :p */
3270 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3272 char modfile[MAXBUF];
3273 ConfValue("module","name",count2,configToken,&config_f);
3274 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3275 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3276 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3277 /* If The File Doesnt exist, Trying to load it
3278 * Will Segfault the IRCd.. So, check to see if
3279 * it Exists, Before Proceeding. */
3280 if (FileExists(modfile))
3282 factory[count] = new ircd_module(modfile);
3283 if (factory[count]->LastError())
3285 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3286 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3289 if (factory[count]->factory)
3291 modules[count] = factory[count]->factory->CreateModule();
3292 /* save the module and the module's classfactory, if
3293 * this isnt done, random crashes can occur :/ */
3294 module_names.push_back(modfile);
3298 log(DEBUG,"Unable to load %s",modfile);
3299 printf("Unable to load %s\nExiting...\n",modfile);
3302 /* Increase the Count */
3307 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3308 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3311 MODCOUNT = count - 1;
3312 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3314 printf("\nInspIRCd is now running!\n");
3316 startup_time = time(NULL);
3320 log(VERBOSE,"Not forking as -nofork was specified");
3324 if (DaemonSeed() == ERROR)
3326 log(DEBUG,"InspIRCd: startup: can't daemonise");
3327 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3333 /* setup select call */
3334 FD_ZERO(&selectFds);
3335 log(DEBUG,"InspIRCd: startup: zero selects");
3336 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3338 for (count = 0; count < portCount; count++)
3340 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3342 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3345 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3347 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3349 else /* well we at least bound to one socket so we'll continue */
3355 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3357 /* if we didn't bind to anything then abort */
3358 if (boundPortCount == 0)
3360 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3365 length = sizeof (client);
3366 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3368 /* main loop, this never returns */
3371 #ifdef _POSIX_PRIORITY_SCHEDULING
3374 // update the status of klines, etc
3381 user_hash::iterator count2 = clientlist.begin();
3383 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3384 // them in a list, then reap the list every second or so.
3385 if (reap_counter>300)
3387 if (fd_reap.size() > 0)
3389 for( int n = 0; n < fd_reap.size(); n++)
3391 Blocking(fd_reap[n]);
3393 NonBlocking(fd_reap[n]);
3402 FD_ZERO(&serverfds);
3405 for (int x = 0; x != UDPportCount; x++)
3408 FD_SET(me[x]->fd, &serverfds);
3414 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3417 for (int x = 0; x != UDPportCount; x++)
3419 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3421 char remotehost[MAXBUF],resolved[MAXBUF];
3422 length = sizeof (client);
3423 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3424 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3425 if(CleanAndResolve(resolved, remotehost) != TRUE)
3427 strlcpy(resolved,remotehost,MAXBUF);
3429 // add to this connections ircd_connector vector
3430 // *FIX* - we need the LOCAL port not the remote port in &client!
3431 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3436 for (int x = 0; x < UDPportCount; x++)
3438 std::deque<std::string> msgs;
3440 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3442 for (int ctr = 0; ctr < msgs.size(); ctr++)
3444 char udp_msg[MAXBUF];
3445 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3446 if (strlen(udp_msg)<1)
3448 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3451 // during a netburst, send all data to all other linked servers
3452 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3454 if (is_uline(tcp_host))
3456 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3458 NetSendToAllExcept(tcp_host,udp_msg);
3462 NetSendToAllExcept(tcp_host,udp_msg);
3464 FOREACH_MOD OnPacketReceive(udp_msg);
3465 handle_link_packet(udp_msg, tcp_host, me[x]);
3472 while (count2 != clientlist.end())
3475 tval.tv_usec = tval.tv_sec = 0;
3477 int total_in_this_set = 0;
3479 user_hash::iterator xcount = count2;
3480 user_hash::iterator endingiter = count2;
3482 if (!count2->second) break;
3485 if (count2->second->fd != 0)
3487 // assemble up to 64 sockets into an fd_set
3488 // to implement a pooling mechanism.
3490 // This should be up to 64x faster than the
3491 // old implementation.
3492 while (total_in_this_set < 64)
3494 if (count2 != clientlist.end())
3496 // we don't check the state of remote users.
3497 if (count2->second->fd > 0)
3499 FD_SET (count2->second->fd, &sfd);
3501 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3502 // their connection class.
3503 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3505 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3506 kill_link(count2->second,"Registration timeout");
3509 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3511 if ((!count2->second->lastping) && (count2->second->registered == 7))
3513 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3514 kill_link(count2->second,"Ping timeout");
3517 Write(count2->second->fd,"PING :%s",ServerName);
3518 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3519 count2->second->lastping = 0;
3520 count2->second->nping = time(NULL)+120;
3524 total_in_this_set++;
3529 endingiter = count2;
3530 count2 = xcount; // roll back to where we were
3536 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3538 // now loop through all of the items in this pool if any are waiting
3539 //if (selectResult2 > 0)
3540 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3543 #ifdef _POSIX_PRIORITY_SCHEDULING
3548 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3550 log(DEBUG,"Reading fd %d",count2a->second->fd);
3551 memset(data, 0, 10240);
3552 result = read(count2a->second->fd, data, 10240);
3557 log(DEBUG,"Read %d characters from socket",result);
3558 userrec* current = count2a->second;
3559 int currfd = current->fd;
3560 char* l = strtok(data,"\n");
3565 if ((floodlines > current->flood) && (current->flood != 0))
3567 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3568 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3569 kill_link(current,"Excess flood");
3572 char sanitized[NetBufferSize];
3573 memset(sanitized, 0, NetBufferSize);
3575 for (int pt = 0; pt < strlen(l); pt++)
3579 sanitized[ptt++] = l[pt];
3582 sanitized[ptt] = '\0';
3583 if (strlen(sanitized))
3587 // we're gonna re-scan to check if the nick is gone, after every
3588 // command - if it has, we're gonna bail
3589 bool find_again = false;
3590 process_buffer(sanitized,current);
3592 // look for the user's record in case it's changed
3593 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3595 if (c2->second->fd == currfd)
3597 // found again, update pointer
3598 current == c2->second;
3607 l = strtok(NULL,"\n");
3612 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3614 log(DEBUG,"killing: %s",count2a->second->nick);
3615 kill_link(count2a->second,strerror(errno));
3619 // result EAGAIN means nothing read
3620 if (result == EAGAIN)
3628 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3629 kill_link(count2a->second,"Client exited");
3630 // must bail here? kill_link removes the hash, corrupting the iterator
3631 log(DEBUG,"Bailing from client exit");
3635 else if (result > 0)
3640 for (int q = 0; q < total_in_this_set; q++)
3642 // there is no iterator += operator :(
3643 //if (count2 != clientlist.end())
3650 // set up select call
3651 for (count = 0; count < boundPortCount; count++)
3653 FD_SET (openSockfd[count], &selectFds);
3657 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3659 /* select is reporting a waiting socket. Poll them all to find out which */
3660 if (selectResult > 0)
3662 char target[MAXBUF], resolved[MAXBUF];
3663 for (count = 0; count < boundPortCount; count++)
3665 if (FD_ISSET (openSockfd[count], &selectFds))
3667 length = sizeof (client);
3668 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3670 address_cache::iterator iter = IP.find(client.sin_addr);
3671 bool iscached = false;
3672 if (iter == IP.end())
3674 /* ip isn't in cache, add it */
3675 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3676 if(CleanAndResolve(resolved, target) != TRUE)
3678 strlcpy(resolved,target,MAXBUF);
3680 /* hostname now in 'target' */
3681 IP[client.sin_addr] = new string(resolved);
3682 /* hostname in cache */
3686 /* found ip (cached) */
3687 strlcpy(resolved, iter->second->c_str(), MAXBUF);
3691 if (incomingSockfd < 0)
3693 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3694 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3698 AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3699 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3706 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3709 close (incomingSockfd);