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;
101 std::string pending_connects[MAXBUF];
110 template<> struct hash<in_addr>
112 template<> struct nspace::hash<in_addr>
115 size_t operator()(const struct in_addr &a) const
118 memcpy(&q,&a,sizeof(size_t));
123 template<> struct hash<string>
125 template<> struct nspace::hash<string>
128 size_t operator()(const string &s) const
131 static struct hash<const char *> strhash;
132 strlcpy(a,s.c_str(),MAXBUF);
143 bool operator()(const string& s1, const string& s2) const
145 char a[MAXBUF],b[MAXBUF];
146 strlcpy(a,s1.c_str(),MAXBUF);
147 strlcpy(b,s2.c_str(),MAXBUF);
148 return (strcasecmp(a,b) == 0);
153 struct InAddr_HashComp
156 bool operator()(const in_addr &s1, const in_addr &s2) const
161 memcpy(&q,&s1,sizeof(size_t));
162 memcpy(&p,&s2,sizeof(size_t));
170 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
171 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
172 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
173 typedef std::deque<command_t> command_table;
179 user_hash clientlist;
182 command_table cmdlist;
189 struct linger linger = { 0 };
190 char MyExecutable[1024];
191 int boundPortCount = 0;
192 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
193 int defaultRoute = 0;
197 long MyKey = C.GenKey();
201 int has_channel(userrec *u, chanrec *c);
202 int usercount(chanrec *c);
203 int usercount_i(chanrec *c);
204 void update_stats_l(int fd,int data_out);
205 char* Passwd(userrec *user);
206 bool IsDenied(userrec *user);
207 void AddWhoWas(userrec* u);
209 std::vector<long> auth_cookies;
210 std::stringstream config_f(stringstream::in | stringstream::out);
216 char Revision[] = "$Revision$";
219 char *v1 = strtok_r(s1," ",&savept);
221 char *v2 = strtok_r(s1," ",&savept);
223 return (long)(atof(v2)*10000);
227 std::string getservername()
232 std::string getserverdesc()
237 std::string getnetworkname()
242 std::string getadminname()
247 std::string getadminemail()
252 std::string getadminnick()
257 void log(int level,char *text, ...)
259 char textbuffer[MAXBUF];
262 struct tm * timeinfo;
263 if (level < LogLevel)
267 timeinfo = localtime (&rawtime);
272 va_start (argsPtr, text);
273 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
275 strlcpy(b,asctime(timeinfo),MAXBUF);
276 b[strlen(b)-1] = ':';
277 fprintf(log_file,"%s %s\n",b,textbuffer);
280 // nofork enabled? display it on terminal too
281 printf("%s %s\n",b,textbuffer);
286 void readfile(file_cache &F, const char* fname)
289 char linebuf[MAXBUF];
291 log(DEBUG,"readfile: loading %s",fname);
293 file = fopen(fname,"r");
298 fgets(linebuf,sizeof(linebuf),file);
299 linebuf[strlen(linebuf)-1]='\0';
300 if (!strcmp(linebuf,""))
306 F.push_back(linebuf);
313 log(DEBUG,"readfile: failed to load file: %s",fname);
315 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
318 void ReadConfig(bool bail, userrec* user)
320 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
321 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF];
323 std::stringstream errstr;
325 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
330 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
338 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
339 while (!errstr.eof())
341 errstr.getline(dataline,1024);
342 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
347 WriteOpers("There were errors in the configuration file:",user->nick);
348 while (!errstr.eof())
350 errstr.getline(dataline,1024);
351 WriteOpers(dataline);
358 ConfValue("server","name",0,ServerName,&config_f);
359 ConfValue("server","description",0,ServerDesc,&config_f);
360 ConfValue("server","network",0,Network,&config_f);
361 ConfValue("admin","name",0,AdminName,&config_f);
362 ConfValue("admin","email",0,AdminEmail,&config_f);
363 ConfValue("admin","nick",0,AdminNick,&config_f);
364 ConfValue("files","motd",0,motd,&config_f);
365 ConfValue("files","rules",0,rules,&config_f);
366 ConfValue("power","diepass",0,diepass,&config_f);
367 ConfValue("power","pause",0,pauseval,&config_f);
368 ConfValue("power","restartpass",0,restartpass,&config_f);
369 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
370 ConfValue("die","value",0,DieValue,&config_f);
371 ConfValue("options","loglevel",0,dbg,&config_f);
372 ConfValue("options","netbuffersize",0,NB,&config_f);
373 ConfValue("options","maxwho",0,MW,&config_f);
374 ConfValue("options","allowhalfop",0,AH,&config_f);
375 ConfValue("options","allowprotect",0,AP,&config_f);
376 ConfValue("options","allowfounder",0,AF,&config_f);
377 ConfValue("dns","server",0,DNSServer,&config_f);
378 ConfValue("dns","timeout",0,DNT,&config_f);
379 NetBufferSize = atoi(NB);
380 MaxWhoResults = atoi(MW);
381 dns_timeout = atoi(DNT);
384 if (!strcmp(DNSServer,""))
385 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
386 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
387 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
388 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
389 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
391 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
392 NetBufferSize = 10240;
394 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
396 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
399 if (!strcmp(dbg,"debug"))
401 if (!strcmp(dbg,"verbose"))
403 if (!strcmp(dbg,"default"))
405 if (!strcmp(dbg,"sparse"))
407 if (!strcmp(dbg,"none"))
410 log(DEFAULT,"Reading message of the day...");
411 readfile(RULES,rules);
412 log(DEFAULT,"Reading connect classes...");
414 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
417 ConfValue("connect","allow",i,Value,&config_f);
418 ConfValue("connect","timeout",i,timeout,&config_f);
419 ConfValue("connect","flood",i,flood,&config_f);
420 if (strcmp(Value,""))
422 strlcpy(c.host,Value,MAXBUF);
424 strlcpy(Value,"",MAXBUF);
425 ConfValue("connect","password",i,Value,&config_f);
426 strlcpy(c.pass,Value,MAXBUF);
427 c.registration_timeout = 90; // default is 2 minutes
428 c.flood = atoi(flood);
431 c.registration_timeout = atoi(timeout);
433 Classes.push_back(c);
434 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
438 ConfValue("connect","deny",i,Value,&config_f);
439 strlcpy(c.host,Value,MAXBUF);
441 Classes.push_back(c);
442 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
446 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
447 read_xline_defaults();
448 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
450 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
453 /* write formatted text to a socket, in same format as printf */
455 void Write(int sock,char *text, ...)
459 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
462 char textbuffer[MAXBUF];
466 va_start (argsPtr, text);
467 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
469 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
473 write(sock,tb,strlen(tb));
474 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
478 /* write a server formatted numeric response to a single socket */
480 void WriteServ(int sock, char* text, ...)
484 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
487 char textbuffer[MAXBUF],tb[MAXBUF];
489 va_start (argsPtr, text);
491 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
493 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
497 write(sock,tb,strlen(tb));
498 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
502 /* write text from an originating user to originating user */
504 void WriteFrom(int sock, userrec *user,char* text, ...)
506 if ((!text) || (!user))
508 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
511 char textbuffer[MAXBUF],tb[MAXBUF];
513 va_start (argsPtr, text);
515 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
517 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
521 write(sock,tb,strlen(tb));
522 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
526 /* write text to an destination user from a source user (e.g. user privmsg) */
528 void WriteTo(userrec *source, userrec *dest,char *data, ...)
530 if ((!dest) || (!data))
532 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
535 char textbuffer[MAXBUF],tb[MAXBUF];
537 va_start (argsPtr, data);
538 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
542 // if no source given send it from the server.
545 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
549 WriteFrom(dest->fd,source,"%s",textbuffer);
553 /* write formatted text from a source user to all users on a channel
554 * including the sender (NOT for privmsg, notice etc!) */
556 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
558 if ((!Ptr) || (!user) || (!text))
560 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
563 char textbuffer[MAXBUF];
565 va_start (argsPtr, text);
566 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
568 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
570 if (has_channel(i->second,Ptr))
572 WriteTo(user,i->second,"%s",textbuffer);
577 /* write formatted text from a source user to all users on a channel
578 * including the sender (NOT for privmsg, notice etc!) doesnt send to
579 * users on remote servers */
581 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
583 if ((!Ptr) || (!text))
585 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
588 char textbuffer[MAXBUF];
590 va_start (argsPtr, text);
591 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
593 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
595 if (has_channel(i->second,Ptr))
597 if (i->second->fd != -1)
601 WriteServ(i->second->fd,"%s",textbuffer);
605 WriteTo(user,i->second,"%s",textbuffer);
613 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
615 if ((!Ptr) || (!user) || (!text))
617 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
620 char textbuffer[MAXBUF];
622 va_start (argsPtr, text);
623 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
625 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
629 if (has_channel(i->second,Ptr))
631 WriteServ(i->second->fd,"%s",textbuffer);
638 /* write formatted text from a source user to all users on a channel except
639 * for the sender (for privmsg etc) */
641 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
643 if ((!Ptr) || (!user) || (!text))
645 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
648 char textbuffer[MAXBUF];
650 va_start (argsPtr, text);
651 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
654 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
658 if (has_channel(i->second,Ptr) && (user != i->second))
660 WriteTo(user,i->second,"%s",textbuffer);
667 std::string GetServerDescription(char* servername)
669 for (int j = 0; j < 32; j++)
673 for (int k = 0; k < me[j]->connectors.size(); k++)
675 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
677 return me[j]->connectors[k].GetDescription();
681 return ServerDesc; // not a remote server that can be found, it must be me.
686 /* write a formatted string to all users who share at least one common
687 * channel, including the source user e.g. for use in NICK */
689 void WriteCommon(userrec *u, char* text, ...)
693 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
697 if (u->registered != 7) {
698 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
702 char textbuffer[MAXBUF];
704 va_start (argsPtr, text);
705 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
708 WriteFrom(u->fd,u,"%s",textbuffer);
710 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
714 if (common_channels(u,i->second) && (i->second != u))
716 WriteFrom(i->second->fd,u,"%s",textbuffer);
722 /* write a formatted string to all users who share at least one common
723 * channel, NOT including the source user e.g. for use in QUIT */
725 void WriteCommonExcept(userrec *u, char* text, ...)
729 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
733 if (u->registered != 7) {
734 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
738 char textbuffer[MAXBUF];
740 va_start (argsPtr, text);
741 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
744 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
748 if ((common_channels(u,i->second)) && (u != i->second))
750 WriteFrom(i->second->fd,u,"%s",textbuffer);
756 void WriteOpers(char* text, ...)
760 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
764 char textbuffer[MAXBUF];
766 va_start (argsPtr, text);
767 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
770 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
774 if (strchr(i->second->modes,'o'))
776 if (strchr(i->second->modes,'s'))
778 // send server notices to all with +s
779 // (TODO: needs SNOMASKs)
780 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
787 // returns TRUE of any users on channel C occupy server 'servername'.
789 bool ChanAnyOnThisServer(chanrec *c,char* servername)
791 log(DEBUG,"ChanAnyOnThisServer");
792 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
794 if (has_channel(i->second,c))
796 if (!strcasecmp(i->second->server,servername))
805 // returns true if user 'u' shares any common channels with any users on server 'servername'
807 bool CommonOnThisServer(userrec* u,const char* servername)
809 log(DEBUG,"ChanAnyOnThisServer");
810 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
812 if ((common_channels(u,i->second)) && (u != i->second))
814 if (!strcasecmp(i->second->server,servername))
816 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
825 void NetSendToCommon(userrec* u, char* s)
828 snprintf(buffer,MAXBUF,"%s",s);
830 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
832 for (int j = 0; j < 32; j++)
836 for (int k = 0; k < me[j]->connectors.size(); k++)
838 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
840 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
848 void NetSendToAll(char* s)
851 snprintf(buffer,MAXBUF,"%s",s);
853 log(DEBUG,"NetSendToAll: '%s'",s);
855 for (int j = 0; j < 32; j++)
859 for (int k = 0; k < me[j]->connectors.size(); k++)
861 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
867 void NetSendToAllAlive(char* s)
870 snprintf(buffer,MAXBUF,"%s",s);
872 log(DEBUG,"NetSendToAllAlive: '%s'",s);
874 for (int j = 0; j < 32; j++)
878 for (int k = 0; k < me[j]->connectors.size(); k++)
880 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
882 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
886 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
894 void NetSendToOne(char* target,char* s)
897 snprintf(buffer,MAXBUF,"%s",s);
899 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
901 for (int j = 0; j < 32; j++)
905 for (int k = 0; k < me[j]->connectors.size(); k++)
907 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
909 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
916 void NetSendToAllExcept(const char* target,char* s)
919 snprintf(buffer,MAXBUF,"%s",s);
921 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
923 for (int j = 0; j < 32; j++)
927 for (int k = 0; k < me[j]->connectors.size(); k++)
929 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
931 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
939 void WriteMode(const char* modes, int flags, const char* text, ...)
941 if ((!text) || (!modes) || (!flags))
943 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
947 char textbuffer[MAXBUF];
949 va_start (argsPtr, text);
950 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
953 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
957 bool send_to_user = false;
962 for (int n = 0; n < strlen(modes); n++)
964 if (!hasumode(i->second,modes[n]))
966 send_to_user = false;
971 else if (flags == WM_OR)
973 send_to_user = false;
974 for (int n = 0; n < strlen(modes); n++)
976 if (hasumode(i->second,modes[n]))
986 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
993 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
995 if ((!text) || (!source))
997 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1002 char textbuffer[MAXBUF];
1004 va_start (argsPtr, text);
1005 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1008 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1012 if (strchr(i->second->modes,'w'))
1014 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1021 char buffer[MAXBUF];
1022 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1023 NetSendToAll(buffer);
1027 /* convert a string to lowercase. Note following special circumstances
1028 * taken from RFC 1459. Many "official" server branches still hold to this
1029 * rule so i will too;
1031 * Because of IRC's scandanavian origin, the characters {}| are
1032 * considered to be the lower case equivalents of the characters []\,
1033 * respectively. This is a critical issue when determining the
1034 * equivalence of two nicknames.
1037 void strlower(char *n)
1043 for (int i = 0; i != strlen(n); i++)
1045 n[i] = tolower(n[i]);
1057 /* Find a user record by nickname and return a pointer to it */
1059 userrec* Find(std::string nick)
1061 user_hash::iterator iter = clientlist.find(nick);
1063 if (iter == clientlist.end())
1064 /* Couldn't find it */
1067 return iter->second;
1070 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1072 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1076 if (i->second->fd == fd)
1078 i->second->bytes_out+=data_out;
1079 i->second->cmds_out++;
1086 /* find a channel record by channel name and return a pointer to it */
1088 chanrec* FindChan(const char* chan)
1092 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1096 chan_hash::iterator iter = chanlist.find(chan);
1098 if (iter == chanlist.end())
1099 /* Couldn't find it */
1102 return iter->second;
1106 void purge_empty_chans(void)
1108 int go_again = 1, purge = 0;
1113 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1116 if (!usercount(i->second))
1118 /* kill the record */
1119 if (i != chanlist.end())
1121 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1122 if (i->second) delete i->second;
1131 log(DEBUG,"skipped purge for %s",i->second->name);
1136 log(DEBUG,"completed channel purge, killed %d",purge);
1140 char scratch[MAXBUF];
1141 char sparam[MAXBUF];
1143 char* chanmodes(chanrec *chan)
1147 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1154 if (chan->noexternal)
1156 strlcat(scratch,"n",MAXMODES);
1158 if (chan->topiclock)
1160 strlcat(scratch,"t",MAXMODES);
1162 if (strcmp(chan->key,""))
1164 strlcat(scratch,"k",MAXMODES);
1168 strlcat(scratch,"l",MAXMODES);
1170 if (chan->inviteonly)
1172 strlcat(scratch,"i",MAXMODES);
1174 if (chan->moderated)
1176 strlcat(scratch,"m",MAXMODES);
1180 strlcat(scratch,"s",MAXMODES);
1182 if (chan->c_private)
1184 strlcat(scratch,"p",MAXMODES);
1186 if (strcmp(chan->key,""))
1188 strlcat(sparam," ",MAXBUF);
1189 strlcat(sparam,chan->key,MAXBUF);
1194 sprintf(foo," %d",chan->limit);
1195 strlcat(sparam,foo,MAXBUF);
1197 if (strlen(chan->custom_modes))
1199 strlcat(scratch,chan->custom_modes,MAXMODES);
1200 for (int z = 0; z < strlen(chan->custom_modes); z++)
1202 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1205 strlcat(sparam," ",MAXBUF);
1206 strlcat(sparam,extparam.c_str(),MAXBUF);
1210 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1211 strlcat(scratch,sparam,MAXMODES);
1216 /* compile a userlist of a channel into a string, each nick seperated by
1217 * spaces and op, voice etc status shown as @ and + */
1219 void userlist(userrec *user,chanrec *c)
1221 if ((!c) || (!user))
1223 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1227 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1228 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1230 if (has_channel(i->second,c))
1232 if (isnick(i->second->nick))
1234 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1236 /* user is +i, and source not on the channel, does not show
1237 * nick in NAMES list */
1240 strlcat(list,cmode(i->second,c),MAXBUF);
1241 strlcat(list,i->second->nick,MAXBUF);
1242 strlcat(list," ",MAXBUF);
1243 if (strlen(list)>(480-NICKMAX))
1245 /* list overflowed into
1246 * multiple numerics */
1247 WriteServ(user->fd,list);
1248 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1253 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1255 WriteServ(user->fd,list);
1259 /* return a count of the users on a specific channel accounting for
1260 * invisible users who won't increase the count. e.g. for /LIST */
1262 int usercount_i(chanrec *c)
1269 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1274 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1278 if (has_channel(i->second,c))
1280 if (isnick(i->second->nick))
1282 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1284 /* user is +i, and source not on the channel, does not show
1285 * nick in NAMES list */
1293 log(DEBUG,"usercount_i: %s %d",c->name,count);
1298 int usercount(chanrec *c)
1305 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1310 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1314 if (has_channel(i->second,c))
1316 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1323 log(DEBUG,"usercount: %s %d",c->name,count);
1328 /* add a channel to a user, creating the record for it if needed and linking
1329 * it to the user record */
1331 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1333 if ((!user) || (!cn))
1335 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1344 strncpy(cname,cn,MAXBUF);
1346 // we MUST declare this wherever we use FOREACH_RESULT
1349 if (strlen(cname) > CHANMAX-1)
1351 cname[CHANMAX-1] = '\0';
1354 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1356 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1358 return NULL; // already on the channel!
1362 if (!FindChan(cname))
1365 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1366 if (MOD_RESULT == 1) {
1370 /* create a new one */
1371 log(DEBUG,"add_channel: creating: %s",cname);
1373 chanlist[cname] = new chanrec();
1375 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1376 chanlist[cname]->topiclock = 1;
1377 chanlist[cname]->noexternal = 1;
1378 chanlist[cname]->created = time(NULL);
1379 strcpy(chanlist[cname]->topic, "");
1380 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1381 chanlist[cname]->topicset = 0;
1382 Ptr = chanlist[cname];
1383 log(DEBUG,"add_channel: created: %s",cname);
1384 /* set created to 2 to indicate user
1385 * is the first in the channel
1386 * and should be given ops */
1392 /* channel exists, just fish out a pointer to its struct */
1393 Ptr = FindChan(cname);
1396 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1398 // the override flag allows us to bypass channel modes
1399 // and bans (used by servers)
1403 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1404 if (MOD_RESULT == 1) {
1408 if (MOD_RESULT == 0)
1411 if (strcmp(Ptr->key,""))
1413 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1416 log(DEBUG,"add_channel: no key given in JOIN");
1417 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1422 log(DEBUG,"key at %p is %s",key,key);
1423 if (strcasecmp(key,Ptr->key))
1425 log(DEBUG,"add_channel: bad key given in JOIN");
1426 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1431 log(DEBUG,"add_channel: no key");
1433 if (Ptr->inviteonly)
1435 log(DEBUG,"add_channel: channel is +i");
1436 if (user->IsInvited(Ptr->name))
1438 /* user was invited to channel */
1439 /* there may be an optional channel NOTICE here */
1443 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1447 log(DEBUG,"add_channel: channel is not +i");
1451 if (usercount(Ptr) == Ptr->limit)
1453 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1458 log(DEBUG,"add_channel: about to walk banlist");
1460 /* check user against the channel banlist */
1463 if (Ptr->bans.size())
1465 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1467 if (match(user->GetFullHost(),i->data))
1469 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1476 log(DEBUG,"add_channel: bans checked");
1481 if ((Ptr) && (user))
1483 user->RemoveInvite(Ptr->name);
1486 log(DEBUG,"add_channel: invites removed");
1491 log(DEBUG,"Overridden checks");
1499 log(DEBUG,"Passed channel checks");
1501 for (int i =0; i != MAXCHANS; i++)
1503 log(DEBUG,"Check location %d",i);
1504 if (user->chans[i].channel == NULL)
1506 log(DEBUG,"Adding into their channel list at location %d",i);
1510 /* first user in is given ops */
1511 user->chans[i].uc_modes = UCMODE_OP;
1515 user->chans[i].uc_modes = 0;
1517 user->chans[i].channel = Ptr;
1518 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1520 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1522 // use the stamdard J token with no privilages.
1523 char buffer[MAXBUF];
1526 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1530 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1532 NetSendToAll(buffer);
1535 log(DEBUG,"Sent JOIN to client");
1539 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1540 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1543 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1544 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1545 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1546 FOREACH_MOD OnUserJoin(user,Ptr);
1550 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1551 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1555 /* remove a channel from a users record, and remove the record from memory
1556 * if the channel has become empty */
1558 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1560 if ((!user) || (!cname))
1562 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1569 if ((!cname) || (!user))
1574 Ptr = FindChan(cname);
1581 FOREACH_MOD OnUserPart(user,Ptr);
1582 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1584 for (int i =0; i != MAXCHANS; i++)
1586 /* zap it from the channel list of the user */
1587 if (user->chans[i].channel == Ptr)
1591 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1595 char buffer[MAXBUF];
1596 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1597 NetSendToAll(buffer);
1606 char buffer[MAXBUF];
1607 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1608 NetSendToAll(buffer);
1611 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1613 user->chans[i].uc_modes = 0;
1614 user->chans[i].channel = NULL;
1615 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1620 /* if there are no users left on the channel */
1621 if (!usercount(Ptr))
1623 chan_hash::iterator iter = chanlist.find(Ptr->name);
1625 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1627 /* kill the record */
1628 if (iter != chanlist.end())
1630 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1631 if (iter->second) delete iter->second;
1632 chanlist.erase(iter);
1638 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1640 if ((!src) || (!user) || (!Ptr) || (!reason))
1642 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1649 if ((!Ptr) || (!user) || (!src))
1654 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1656 if (!has_channel(user,Ptr))
1658 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1663 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1665 if (MOD_RESULT == ACR_DENY)
1668 if (MOD_RESULT == ACR_DEFAULT)
1670 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1672 if (cstatus(src,Ptr) == STATUS_HOP)
1674 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1678 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1685 for (int i =0; i != MAXCHANS; i++)
1687 /* zap it from the channel list of the user */
1688 if (user->chans[i].channel)
1689 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1691 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1692 user->chans[i].uc_modes = 0;
1693 user->chans[i].channel = NULL;
1694 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1699 /* if there are no users left on the channel */
1700 if (!usercount(Ptr))
1702 chan_hash::iterator iter = chanlist.find(Ptr->name);
1704 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1706 /* kill the record */
1707 if (iter != chanlist.end())
1709 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1710 if (iter->second) delete iter->second;
1711 chanlist.erase(iter);
1719 /* This function pokes and hacks at a parameter list like the following:
1721 * PART #winbot, #darkgalaxy :m00!
1723 * to turn it into a series of individual calls like this:
1725 * PART #winbot :m00!
1726 * PART #darkgalaxy :m00!
1728 * The seperate calls are sent to a callback function provided by the caller
1729 * (the caller will usually call itself recursively). The callback function
1730 * must be a command handler. Calling this function on a line with no list causes
1731 * no action to be taken. You must provide a starting and ending parameter number
1732 * where the range of the list can be found, useful if you have a terminating
1733 * parameter as above which is actually not part of the list, or parameters
1734 * before the actual list as well. This code is used by many functions which
1735 * can function as "one to list" (see the RFC) */
1737 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1742 char blog[32][MAXBUF];
1743 char blog2[32][MAXBUF];
1744 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1745 char keystr[MAXBUF];
1748 for (int i = 0; i <32; i++)
1751 for (int i = 0; i <32; i++)
1752 strcpy(blog2[i],"");
1755 for (int i = 0; i <10; i++)
1759 parameters[i] = moo;
1764 if (pcnt > 1) /* we have a key to copy */
1766 strlcpy(keystr,parameters[1],MAXBUF);
1770 if (!parameters[start])
1774 if (!strchr(parameters[start],','))
1779 for (int i = start; i <= end; i++)
1783 strlcat(plist,parameters[i],MAXBUF);
1791 for (int i = 0; i < t; i++)
1793 if (plist[i] == ',')
1796 strlcpy(blog[j++],param,MAXBUF);
1800 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1805 strlcpy(blog[j++],param,MAXBUF);
1808 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1813 if ((joins) && (keystr))
1815 if (strchr(keystr,','))
1819 t2 = strlen(keystr);
1820 for (int i = 0; i < t2; i++)
1822 if (keystr[i] == ',')
1825 strlcpy(blog2[j++],param,MAXBUF);
1829 strlcpy(blog2[j++],param,MAXBUF);
1834 for (j = 0; j < total; j++)
1840 for (q = end; q < pcnt-1; q++)
1842 if (parameters[q+1])
1844 pars[q-end+1] = parameters[q+1];
1847 if ((joins) && (parameters[1]))
1858 /* repeatedly call the function with the hacked parameter list */
1859 if ((joins) && (pcnt > 1))
1863 // pars[1] already set up and containing key from blog2[j]
1868 pars[1] = parameters[1];
1874 fn(pars,pcnt-(end-start),u);
1883 void kill_link(userrec *user,const char* r)
1885 user_hash::iterator iter = clientlist.find(user->nick);
1887 char reason[MAXBUF];
1889 strncpy(reason,r,MAXBUF);
1891 if (strlen(reason)>MAXQUIT)
1893 reason[MAXQUIT-1] = '\0';
1896 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1897 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1898 log(DEBUG,"closing fd %d",user->fd);
1900 /* bugfix, cant close() a nonblocking socket (sux!) */
1901 if (user->registered == 7) {
1902 FOREACH_MOD OnUserQuit(user);
1903 WriteCommonExcept(user,"QUIT :%s",reason);
1905 // Q token must go to ALL servers!!!
1906 char buffer[MAXBUF];
1907 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1908 NetSendToAll(buffer);
1911 /* push the socket on a stack of sockets due to be closed at the next opportunity
1912 * 'Client exited' is an exception to this as it means the client side has already
1913 * closed the socket, we don't need to do it.
1915 fd_reap.push_back(user->fd);
1917 bool do_purge = false;
1919 if (user->registered == 7) {
1920 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1924 if (iter != clientlist.end())
1926 log(DEBUG,"deleting user hash value %d",iter->second);
1927 if ((iter->second) && (user->registered == 7)) {
1928 if (iter->second) delete iter->second;
1930 clientlist.erase(iter);
1933 if (user->registered == 7) {
1934 purge_empty_chans();
1939 void kill_link_silent(userrec *user,const char* r)
1941 user_hash::iterator iter = clientlist.find(user->nick);
1943 char reason[MAXBUF];
1945 strncpy(reason,r,MAXBUF);
1947 if (strlen(reason)>MAXQUIT)
1949 reason[MAXQUIT-1] = '\0';
1952 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1953 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1954 log(DEBUG,"closing fd %d",user->fd);
1956 /* bugfix, cant close() a nonblocking socket (sux!) */
1957 if (user->registered == 7) {
1958 FOREACH_MOD OnUserQuit(user);
1959 WriteCommonExcept(user,"QUIT :%s",reason);
1961 // Q token must go to ALL servers!!!
1962 char buffer[MAXBUF];
1963 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1964 NetSendToAll(buffer);
1967 /* push the socket on a stack of sockets due to be closed at the next opportunity
1968 * 'Client exited' is an exception to this as it means the client side has already
1969 * closed the socket, we don't need to do it.
1971 fd_reap.push_back(user->fd);
1973 bool do_purge = false;
1975 if (iter != clientlist.end())
1977 log(DEBUG,"deleting user hash value %d",iter->second);
1978 if ((iter->second) && (user->registered == 7)) {
1979 if (iter->second) delete iter->second;
1981 clientlist.erase(iter);
1984 if (user->registered == 7) {
1985 purge_empty_chans();
1991 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1993 char* Passwd(userrec *user)
1995 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1997 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2005 bool IsDenied(userrec *user)
2007 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2009 if (match(user->host,i->host) && (i->type == CC_DENY))
2020 /* sends out an error notice to all connected clients (not to be used
2023 void send_error(char *s)
2025 log(DEBUG,"send_error: %s",s);
2026 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2028 if (isnick(i->second->nick))
2030 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2034 // fix - unregistered connections receive ERROR, not NOTICE
2035 Write(i->second->fd,"ERROR :%s",s);
2040 void Error(int status)
2042 signal (SIGALRM, SIG_IGN);
2043 signal (SIGPIPE, SIG_IGN);
2044 signal (SIGTERM, SIG_IGN);
2045 signal (SIGABRT, SIG_IGN);
2046 signal (SIGSEGV, SIG_IGN);
2047 signal (SIGURG, SIG_IGN);
2048 signal (SIGKILL, SIG_IGN);
2049 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2050 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2055 int main(int argc, char **argv)
2059 log(DEBUG,"*** InspIRCd starting up!");
2060 if (!FileExists(CONFIG_FILE))
2062 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2063 log(DEBUG,"main: no config");
2064 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2068 for (int i = 1; i < argc; i++)
2070 if (!strcmp(argv[i],"-nofork")) {
2073 if (!strcmp(argv[i],"-wait")) {
2078 strlcpy(MyExecutable,argv[0],MAXBUF);
2080 if (InspIRCd() == ERROR)
2082 log(DEBUG,"main: daemon function bailed");
2083 printf("ERROR: could not initialise. Shutting down.\n");
2090 template<typename T> inline string ConvToStr(const T &in)
2093 if (!(tmp << in)) return string();
2097 /* re-allocates a nick in the user_hash after they change nicknames,
2098 * returns a pointer to the new user as it may have moved */
2100 userrec* ReHashNick(char* Old, char* New)
2102 user_hash::iterator newnick;
2103 user_hash::iterator oldnick = clientlist.find(Old);
2105 log(DEBUG,"ReHashNick: %s %s",Old,New);
2107 if (!strcasecmp(Old,New))
2109 log(DEBUG,"old nick is new nick, skipping");
2110 return oldnick->second;
2113 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2115 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2117 clientlist[New] = new userrec();
2118 clientlist[New] = oldnick->second;
2119 clientlist.erase(oldnick);
2121 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2123 return clientlist[New];
2126 /* adds or updates an entry in the whowas list */
2127 void AddWhoWas(userrec* u)
2129 user_hash::iterator iter = whowas.find(u->nick);
2130 userrec *a = new userrec();
2131 strlcpy(a->nick,u->nick,NICKMAX);
2132 strlcpy(a->ident,u->ident,64);
2133 strlcpy(a->dhost,u->dhost,256);
2134 strlcpy(a->host,u->host,256);
2135 strlcpy(a->fullname,u->fullname,128);
2136 strlcpy(a->server,u->server,256);
2137 a->signon = u->signon;
2139 /* MAX_WHOWAS: max number of /WHOWAS items
2140 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2141 * can be replaced by a newer one
2144 if (iter == whowas.end())
2146 if (whowas.size() == WHOWAS_MAX)
2148 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2150 // 3600 seconds in an hour ;)
2151 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2153 if (i->second) delete i->second;
2155 log(DEBUG,"added WHOWAS entry, purged an old record");
2162 log(DEBUG,"added fresh WHOWAS entry");
2163 whowas[a->nick] = a;
2168 log(DEBUG,"updated WHOWAS entry");
2169 if (iter->second) delete iter->second;
2175 /* add a client connection to the sockets list */
2176 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2180 char resolved[MAXBUF];
2183 user_hash::iterator iter;
2185 tempnick = ConvToStr(socket) + "-unknown";
2186 sprintf(tn2,"%d-unknown",socket);
2188 iter = clientlist.find(tempnick);
2190 if (iter != clientlist.end()) return;
2193 * It is OK to access the value here this way since we know
2194 * it exists, we just created it above.
2196 * At NO other time should you access a value in a map or a
2197 * hash_map this way.
2199 clientlist[tempnick] = new userrec();
2201 NonBlocking(socket);
2202 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2204 clientlist[tempnick]->fd = socket;
2205 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2206 strncpy(clientlist[tempnick]->host, host,160);
2207 strncpy(clientlist[tempnick]->dhost, host,160);
2208 strncpy(clientlist[tempnick]->server, ServerName,256);
2209 strncpy(clientlist[tempnick]->ident, "unknown",9);
2210 clientlist[tempnick]->registered = 0;
2211 clientlist[tempnick]->signon = time(NULL);
2212 clientlist[tempnick]->nping = time(NULL)+240;
2213 clientlist[tempnick]->lastping = 1;
2214 clientlist[tempnick]->port = port;
2215 strncpy(clientlist[tempnick]->ip,ip,32);
2217 // set the registration timeout for this user
2218 unsigned long class_regtimeout = 90;
2219 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2221 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2223 class_regtimeout = (unsigned long)i->registration_timeout;
2228 int class_flood = 0;
2229 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2231 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2233 class_flood = i->flood;
2238 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2239 clientlist[tempnick]->flood = class_flood;
2241 for (int i = 0; i < MAXCHANS; i++)
2243 clientlist[tempnick]->chans[i].channel = NULL;
2244 clientlist[tempnick]->chans[i].uc_modes = 0;
2247 if (clientlist.size() == MAXCLIENTS)
2248 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2250 char* r = matches_zline(ip);
2253 char reason[MAXBUF];
2254 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2255 kill_link(clientlist[tempnick],reason);
2262 return clientlist.size();
2266 int usercount_invisible(void)
2270 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2272 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2277 int usercount_opers(void)
2281 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2283 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2288 int usercount_unknown(void)
2292 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2294 if ((i->second->fd) && (i->second->registered != 7))
2300 long chancount(void)
2302 return chanlist.size();
2305 long count_servs(void)
2308 //for (int j = 0; j < 255; j++)
2310 // if (servers[j] != NULL)
2316 long servercount(void)
2318 return count_servs()+1;
2324 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2326 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2332 void ShowMOTD(userrec *user)
2336 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2339 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2340 for (int i = 0; i != MOTD.size(); i++)
2342 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2344 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2347 void ShowRULES(userrec *user)
2351 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2354 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2355 for (int i = 0; i != RULES.size(); i++)
2357 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2359 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2362 /* shows the message of the day, and any other on-logon stuff */
2363 void FullConnectUser(userrec* user)
2365 user->registered = 7;
2366 user->idle_lastmsg = time(NULL);
2367 log(DEBUG,"ConnectUser: %s",user->nick);
2369 if (strcmp(Passwd(user),"") && (!user->haspassed))
2371 kill_link(user,"Invalid password");
2376 kill_link(user,"Unauthorised connection");
2380 char match_against[MAXBUF];
2381 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2382 char* r = matches_gline(match_against);
2385 char reason[MAXBUF];
2386 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2387 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);
2400 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2401 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2402 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2403 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2404 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2405 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2406 std::stringstream v;
2407 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2408 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2409 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2410 v << std::string(Network);
2411 std::string data005 = v.str();
2412 FOREACH_MOD On005Numeric(data005);
2413 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2414 // so i'd better split it :)
2415 std::stringstream out(data005);
2416 std::string token = "";
2417 std::string line5 = "";
2418 int token_counter = 0;
2422 line5 = line5 + token + " ";
2424 if ((token_counter >= 13) || (out.eof() == true))
2426 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2432 FOREACH_MOD OnUserConnect(user);
2433 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2435 char buffer[MAXBUF];
2436 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);
2437 NetSendToAll(buffer);
2440 // handles any connects where DNS isnt done yet, times out stale dns queries on users, and lets completed queries connect.
2441 void HandlePendingConnects()
2443 for (long i = 0; i < MAXBUF; i++)
2445 std::string t = pending_connects[i];
2448 userrec* a = Find(t);
2451 // this user's dns is done now.
2452 if ((a->dns_done) && (a->registered == 3))
2454 FullConnectUser(a); // attack! attack!....
2455 pending_connects[i] = "";
2456 return; // ...RUN AWAY! RUN AWAY!
2458 // this users dns is NOT done, but its timed out.
2459 if ((time(NULL) > a->signon+dns_timeout) && (a->registered == 3))
2461 WriteServ(a->fd,"NOTICE Auth :Failed to resolve your hostname, using your IP address instead.");
2463 pending_connects[i] = "";
2471 /* shows the message of the day, and any other on-logon stuff */
2472 void ConnectUser(userrec *user)
2474 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2477 FullConnectUser(user);
2481 // add them to the pending queue
2482 for (int i = 0; i < MAXBUF; i++)
2484 pending_connects[i] = std::string(user->nick);
2490 void handle_version(char **parameters, int pcnt, userrec *user)
2492 char Revision[] = "$Revision$";
2494 char *s1 = Revision;
2496 char *v1 = strtok_r(s1," ",&savept);
2498 char *v2 = strtok_r(s1," ",&savept);
2501 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2505 // calls a handler function for a command
2507 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2509 for (int i = 0; i < cmdlist.size(); i++)
2511 if (!strcasecmp(cmdlist[i].command,commandname))
2513 if (cmdlist[i].handler_function)
2515 if (pcnt>=cmdlist[i].min_params)
2517 if (strchr(user->modes,cmdlist[i].flags_needed))
2519 cmdlist[i].handler_function(parameters,pcnt,user);
2527 void DoSplitEveryone()
2529 bool go_again = true;
2533 for (int i = 0; i < 32; i++)
2537 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2539 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2542 j->CloseConnection();
2543 me[i]->connectors.erase(j);
2551 log(DEBUG,"Removed server. Will remove clients...");
2552 // iterate through the userlist and remove all users on this server.
2553 // because we're dealing with a mesh, we dont have to deal with anything
2554 // "down-route" from this server (nice huh)
2556 char reason[MAXBUF];
2560 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2562 if (strcasecmp(u->second->server,ServerName))
2564 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2565 kill_link(u->second,reason);
2575 char islast(const char* s)
2578 for (int j = 0; j < 32; j++)
2582 for (int k = 0; k < me[j]->connectors.size(); k++)
2584 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2588 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2598 long map_count(const char* s)
2601 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2603 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2609 void force_nickchange(userrec* user,const char* newnick)
2616 FOREACH_RESULT(OnUserPreNick(user,newnick));
2618 kill_link(user,"Nickname collision");
2621 if (matches_qline(newnick))
2623 kill_link(user,"Nickname collision");
2631 strncpy(nick,newnick,MAXBUF);
2633 if (user->registered == 7)
2637 handle_nick(pars,1,user);
2643 int process_parameters(char **command_p,char *parameters)
2648 q = strlen(parameters);
2651 /* no parameters, command_p invalid! */
2654 if (parameters[0] == ':')
2656 command_p[0] = parameters+1;
2661 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2663 /* only one parameter */
2664 command_p[0] = parameters;
2665 if (parameters[0] == ':')
2667 if (strchr(parameters,' ') != NULL)
2675 command_p[j++] = parameters;
2676 for (int i = 0; i <= q; i++)
2678 if (parameters[i] == ' ')
2680 command_p[j++] = parameters+i+1;
2681 parameters[i] = '\0';
2682 if (command_p[j-1][0] == ':')
2684 *command_p[j-1]++; /* remove dodgy ":" */
2686 /* parameter like this marks end of the sequence */
2690 return j; /* returns total number of items in the list */
2693 void process_command(userrec *user, char* cmd)
2697 char *command_p[127];
2698 char p[MAXBUF], temp[MAXBUF];
2699 int i, j, items, cmd_found;
2701 for (int i = 0; i < 127; i++)
2702 command_p[i] = NULL;
2712 if (!strcmp(cmd,""))
2717 int total_params = 0;
2720 for (int q = 0; q < strlen(cmd)-1; q++)
2722 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2725 // found a 'trailing', we dont count them after this.
2733 // another phidjit bug...
2734 if (total_params > 126)
2736 //kill_link(user,"Protocol violation (1)");
2737 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2741 strlcpy(temp,cmd,MAXBUF);
2743 std::string tmp = cmd;
2744 for (int i = 0; i <= MODCOUNT; i++)
2746 std::string oldtmp = tmp;
2747 modules[i]->OnServerRaw(tmp,true,user);
2750 log(DEBUG,"A Module changed the input string!");
2751 log(DEBUG,"New string: %s",tmp.c_str());
2752 log(DEBUG,"Old string: %s",oldtmp.c_str());
2756 strlcpy(cmd,tmp.c_str(),MAXBUF);
2757 strlcpy(temp,cmd,MAXBUF);
2759 if (!strchr(cmd,' '))
2761 /* no parameters, lets skip the formalities and not chop up
2763 log(DEBUG,"About to preprocess command with no params");
2765 command_p[0] = NULL;
2767 for (int i = 0; i <= strlen(cmd); i++)
2769 cmd[i] = toupper(cmd[i]);
2771 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2778 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2779 for (int i = 0; i < strlen(temp); i++)
2781 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2787 /* split the full string into a command plus parameters */
2791 if (strchr(cmd,' '))
2793 for (int i = 0; i <= strlen(cmd); i++)
2795 /* capitalise the command ONLY, leave params intact */
2796 cmd[i] = toupper(cmd[i]);
2797 /* are we nearly there yet?! :P */
2801 parameters = cmd+i+1;
2809 for (int i = 0; i <= strlen(cmd); i++)
2811 cmd[i] = toupper(cmd[i]);
2818 if (strlen(command)>MAXCOMMAND)
2820 //kill_link(user,"Protocol violation (2)");
2821 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2825 for (int x = 0; x < strlen(command); x++)
2827 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2829 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2831 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2833 //kill_link(user,"Protocol violation (3)");
2834 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2841 for (int i = 0; i != cmdlist.size(); i++)
2843 if (strcmp(cmdlist[i].command,""))
2845 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2847 log(DEBUG,"Found matching command");
2851 if (strcmp(parameters,""))
2853 items = process_parameters(command_p,parameters);
2858 command_p[0] = NULL;
2864 command_p[0] = NULL;
2869 log(DEBUG,"Processing command");
2871 /* activity resets the ping pending timer */
2872 user->nping = time(NULL) + 120;
2873 if ((items) < cmdlist[i].min_params)
2875 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2876 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2879 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2881 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2882 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2886 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2888 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2889 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2893 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2895 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2897 if ((!isnick(user->nick)) || (user->registered != 7))
2899 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2900 WriteServ(user->fd,"451 %s :You have not registered",command);
2904 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2906 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2907 if (cmdlist[i].handler_function)
2909 /* ikky /stats counters */
2914 user->bytes_in += strlen(temp);
2917 cmdlist[i].use_count++;
2918 cmdlist[i].total_bytes+=strlen(temp);
2921 /* WARNING: nothing may come after the
2922 * command handler call, as the handler
2923 * may free the user structure! */
2925 cmdlist[i].handler_function(command_p,items,user);
2931 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2932 WriteServ(user->fd,"451 %s :You have not registered",command);
2940 if ((!cmd_found) && (user))
2942 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2943 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2948 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2951 /* create the command and push it onto the table */
2952 strlcpy(comm.command,cmd,MAXBUF);
2953 comm.handler_function = f;
2954 comm.flags_needed = flags;
2955 comm.min_params = minparams;
2957 comm.total_bytes = 0;
2958 cmdlist.push_back(comm);
2959 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2962 void SetupCommandTable(void)
2964 createcommand("USER",handle_user,0,4);
2965 createcommand("NICK",handle_nick,0,1);
2966 createcommand("QUIT",handle_quit,0,0);
2967 createcommand("VERSION",handle_version,0,0);
2968 createcommand("PING",handle_ping,0,1);
2969 createcommand("PONG",handle_pong,0,1);
2970 createcommand("ADMIN",handle_admin,0,0);
2971 createcommand("PRIVMSG",handle_privmsg,0,2);
2972 createcommand("INFO",handle_info,0,0);
2973 createcommand("TIME",handle_time,0,0);
2974 createcommand("WHOIS",handle_whois,0,1);
2975 createcommand("WALLOPS",handle_wallops,'o',1);
2976 createcommand("NOTICE",handle_notice,0,2);
2977 createcommand("JOIN",handle_join,0,1);
2978 createcommand("NAMES",handle_names,0,1);
2979 createcommand("PART",handle_part,0,1);
2980 createcommand("KICK",handle_kick,0,2);
2981 createcommand("MODE",handle_mode,0,1);
2982 createcommand("TOPIC",handle_topic,0,1);
2983 createcommand("WHO",handle_who,0,1);
2984 createcommand("MOTD",handle_motd,0,0);
2985 createcommand("RULES",handle_rules,0,0);
2986 createcommand("OPER",handle_oper,0,2);
2987 createcommand("LIST",handle_list,0,0);
2988 createcommand("DIE",handle_die,'o',1);
2989 createcommand("RESTART",handle_restart,'o',1);
2990 createcommand("KILL",handle_kill,'o',2);
2991 createcommand("REHASH",handle_rehash,'o',0);
2992 createcommand("LUSERS",handle_lusers,0,0);
2993 createcommand("STATS",handle_stats,0,1);
2994 createcommand("USERHOST",handle_userhost,0,1);
2995 createcommand("AWAY",handle_away,0,0);
2996 createcommand("ISON",handle_ison,0,0);
2997 createcommand("SUMMON",handle_summon,0,0);
2998 createcommand("USERS",handle_users,0,0);
2999 createcommand("INVITE",handle_invite,0,2);
3000 createcommand("PASS",handle_pass,0,1);
3001 createcommand("TRACE",handle_trace,'o',0);
3002 createcommand("WHOWAS",handle_whowas,0,1);
3003 createcommand("CONNECT",handle_connect,'o',1);
3004 createcommand("SQUIT",handle_squit,'o',0);
3005 createcommand("MODULES",handle_modules,'o',0);
3006 createcommand("LINKS",handle_links,0,0);
3007 createcommand("MAP",handle_map,0,0);
3008 createcommand("KLINE",handle_kline,'o',1);
3009 createcommand("GLINE",handle_gline,'o',1);
3010 createcommand("ZLINE",handle_zline,'o',1);
3011 createcommand("QLINE",handle_qline,'o',1);
3012 createcommand("SERVER",handle_server,0,0);
3015 void process_buffer(const char* cmdbuf,userrec *user)
3019 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3026 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3029 if (!strcmp(cmdbuf,""))
3033 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3035 strlcpy(cmd,cmdbuf,MAXBUF);
3036 if (!strcmp(cmd,""))
3040 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3042 cmd[strlen(cmd)-1] = '\0';
3044 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3046 cmd[strlen(cmd)-1] = '\0';
3049 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3051 cmd[strlen(cmd)-1] = '\0';
3054 if (!strcmp(cmd,""))
3058 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3060 if ((user) && (cmd))
3062 process_command(user,cmd);
3066 void DoSync(serverrec* serv, char* tcp_host)
3069 log(DEBUG,"Sending sync");
3070 // send start of sync marker: Y <timestamp>
3071 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3072 // except the ones its receiving it from.
3073 snprintf(data,MAXBUF,"Y %d",time(NULL));
3074 serv->SendPacket(data,tcp_host);
3075 // send users and channels
3076 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3078 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);
3079 serv->SendPacket(data,tcp_host);
3080 if (strchr(u->second->modes,'o'))
3082 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3083 serv->SendPacket(data,tcp_host);
3085 for (int i = 0; i <= MODCOUNT; i++)
3087 string_list l = modules[i]->OnUserSync(u->second);
3088 for (int j = 0; j < l.size(); j++)
3090 strlcpy(data,l[j].c_str(),MAXBUF);
3091 serv->SendPacket(data,tcp_host);
3094 if (strcmp(chlist(u->second),""))
3096 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3097 serv->SendPacket(data,tcp_host);
3100 // send channel modes, topics etc...
3101 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3103 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3104 serv->SendPacket(data,tcp_host);
3105 for (int i = 0; i <= MODCOUNT; i++)
3107 string_list l = modules[i]->OnChannelSync(c->second);
3108 for (int j = 0; j < l.size(); j++)
3110 strlcpy(data,l[j].c_str(),MAXBUF);
3111 serv->SendPacket(data,tcp_host);
3114 if (strcmp(c->second->topic,""))
3116 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3117 serv->SendPacket(data,tcp_host);
3119 // send current banlist
3121 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3123 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3124 serv->SendPacket(data,tcp_host);
3127 // sync global zlines, glines, etc
3128 sync_xlines(serv,tcp_host);
3130 for (int j = 0; j < 32; j++)
3134 for (int k = 0; k < me[j]->connectors.size(); k++)
3136 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3138 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3139 serv->SendPacket(data,tcp_host);
3140 NetSendMyRoutingTable();
3146 snprintf(data,MAXBUF,"F %d",time(NULL));
3147 serv->SendPacket(data,tcp_host);
3148 log(DEBUG,"Sent sync");
3149 // ircd sends its serverlist after the end of sync here
3153 void NetSendMyRoutingTable()
3155 // send out a line saying what is reachable to us.
3156 // E.g. if A is linked to B C and D, send out:
3158 // if its only linked to B and D send out:
3160 // if it has no links, dont even send out the line at all.
3161 char buffer[MAXBUF];
3162 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3163 bool sendit = false;
3164 for (int i = 0; i < 32; i++)
3168 for (int j = 0; j < me[i]->connectors.size(); j++)
3170 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3172 strlcat(buffer," ",MAXBUF);
3173 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3180 NetSendToAll(buffer);
3184 void DoSplit(const char* params)
3186 bool go_again = true;
3190 for (int i = 0; i < 32; i++)
3194 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3196 if (!strcasecmp(j->GetServerName().c_str(),params))
3199 j->CloseConnection();
3200 me[i]->connectors.erase(j);
3208 log(DEBUG,"Removed server. Will remove clients...");
3209 // iterate through the userlist and remove all users on this server.
3210 // because we're dealing with a mesh, we dont have to deal with anything
3211 // "down-route" from this server (nice huh)
3213 char reason[MAXBUF];
3214 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3218 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3220 if (!strcasecmp(u->second->server,params))
3222 kill_link(u->second,reason);
3230 // removes a server. Will NOT remove its users!
3232 void RemoveServer(const char* name)
3234 bool go_again = true;
3238 for (int i = 0; i < 32; i++)
3242 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3244 if (!strcasecmp(j->GetServerName().c_str(),name))
3247 j->CloseConnection();
3248 me[i]->connectors.erase(j);
3259 int reap_counter = 0;
3263 struct sockaddr_in client,server;
3264 char addrs[MAXBUF][255];
3265 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3268 int selectResult = 0, selectResult2 = 0;
3269 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3270 char resolvedHost[MAXBUF];
3274 log_file = fopen("ircd.log","a+");
3277 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3281 log(DEBUG,"InspIRCd: startup: begin");
3285 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3287 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3289 SetupCommandTable();
3290 log(DEBUG,"InspIRCd: startup: default command table set up");
3292 ReadConfig(true,NULL);
3293 if (strcmp(DieValue,""))
3295 printf("WARNING: %s\n\n",DieValue);
3298 log(DEBUG,"InspIRCd: startup: read config");
3300 int count2 = 0, count3 = 0;
3302 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3304 ConfValue("bind","port",count,configToken,&config_f);
3305 ConfValue("bind","address",count,Addr,&config_f);
3306 ConfValue("bind","type",count,Type,&config_f);
3307 if (!strcmp(Type,"servers"))
3309 char Default[MAXBUF];
3310 strcpy(Default,"no");
3311 ConfValue("bind","default",count,Default,&config_f);
3312 if (strchr(Default,'y'))
3314 defaultRoute = count3;
3315 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3317 me[count3] = new serverrec(ServerName,100L,false);
3318 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3320 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3329 ports[count2] = atoi(configToken);
3330 strlcpy(addrs[count2],Addr,256);
3333 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3336 UDPportCount = count3;
3338 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3340 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3344 /* BugFix By Craig! :p */
3346 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3348 char modfile[MAXBUF];
3349 ConfValue("module","name",count2,configToken,&config_f);
3350 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3351 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3352 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3353 /* If The File Doesnt exist, Trying to load it
3354 * Will Segfault the IRCd.. So, check to see if
3355 * it Exists, Before Proceeding. */
3356 if (FileExists(modfile))
3358 factory[count] = new ircd_module(modfile);
3359 if (factory[count]->LastError())
3361 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3362 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3365 if (factory[count]->factory)
3367 modules[count] = factory[count]->factory->CreateModule();
3368 /* save the module and the module's classfactory, if
3369 * this isnt done, random crashes can occur :/ */
3370 module_names.push_back(modfile);
3374 log(DEBUG,"Unable to load %s",modfile);
3375 printf("Unable to load %s\nExiting...\n",modfile);
3378 /* Increase the Count */
3383 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3384 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3387 MODCOUNT = count - 1;
3388 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3390 printf("\nInspIRCd is now running!\n");
3392 startup_time = time(NULL);
3396 log(VERBOSE,"Not forking as -nofork was specified");
3400 if (DaemonSeed() == ERROR)
3402 log(DEBUG,"InspIRCd: startup: can't daemonise");
3403 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3409 /* setup select call */
3410 FD_ZERO(&selectFds);
3411 log(DEBUG,"InspIRCd: startup: zero selects");
3412 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3414 for (count = 0; count < portCount; count++)
3416 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3418 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3421 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3423 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3425 else /* well we at least bound to one socket so we'll continue */
3431 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3433 /* if we didn't bind to anything then abort */
3434 if (boundPortCount == 0)
3436 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3441 length = sizeof (client);
3442 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3444 /* main loop, this never returns */
3447 #ifdef _POSIX_PRIORITY_SCHEDULING
3450 // update the status of klines, etc
3460 // handle pending connects
3461 HandlePendingConnects();
3463 user_hash::iterator count2 = clientlist.begin();
3465 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3466 // them in a list, then reap the list every second or so.
3467 if (reap_counter>300)
3469 if (fd_reap.size() > 0)
3471 for( int n = 0; n < fd_reap.size(); n++)
3473 //Blocking(fd_reap[n]);
3475 shutdown (fd_reap[n],2);
3476 //NonBlocking(fd_reap[n]);
3485 FD_ZERO(&serverfds);
3488 for (int x = 0; x != UDPportCount; x++)
3491 FD_SET(me[x]->fd, &serverfds);
3497 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3500 for (int x = 0; x != UDPportCount; x++)
3502 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3504 char remotehost[MAXBUF],resolved[MAXBUF];
3505 length = sizeof (client);
3506 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3507 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3508 if(CleanAndResolve(resolved, remotehost) != TRUE)
3510 strlcpy(resolved,remotehost,MAXBUF);
3512 // add to this connections ircd_connector vector
3513 // *FIX* - we need the LOCAL port not the remote port in &client!
3514 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3519 for (int x = 0; x < UDPportCount; x++)
3521 std::deque<std::string> msgs;
3523 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3525 for (int ctr = 0; ctr < msgs.size(); ctr++)
3527 char udp_msg[MAXBUF];
3528 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3529 if (strlen(udp_msg)<1)
3531 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3534 // during a netburst, send all data to all other linked servers
3535 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3537 if (is_uline(tcp_host))
3539 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3541 NetSendToAllExcept(tcp_host,udp_msg);
3545 NetSendToAllExcept(tcp_host,udp_msg);
3547 FOREACH_MOD OnPacketReceive(udp_msg);
3548 handle_link_packet(udp_msg, tcp_host, me[x]);
3555 while (count2 != clientlist.end())
3558 tval.tv_usec = tval.tv_sec = 0;
3560 int total_in_this_set = 0;
3562 user_hash::iterator xcount = count2;
3563 user_hash::iterator endingiter = count2;
3565 if (!count2->second) break;
3568 if (count2->second->fd != 0)
3570 // assemble up to 64 sockets into an fd_set
3571 // to implement a pooling mechanism.
3573 // This should be up to 64x faster than the
3574 // old implementation.
3575 while (total_in_this_set < 64)
3577 if (count2 != clientlist.end())
3579 // we don't check the state of remote users.
3580 if (count2->second->fd > 0)
3582 FD_SET (count2->second->fd, &sfd);
3584 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3585 // their connection class.
3586 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3588 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3589 kill_link(count2->second,"Registration timeout");
3592 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3594 if ((!count2->second->lastping) && (count2->second->registered == 7))
3596 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3597 kill_link(count2->second,"Ping timeout");
3600 Write(count2->second->fd,"PING :%s",ServerName);
3601 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3602 count2->second->lastping = 0;
3603 count2->second->nping = time(NULL)+120;
3607 total_in_this_set++;
3612 endingiter = count2;
3613 count2 = xcount; // roll back to where we were
3619 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3621 // now loop through all of the items in this pool if any are waiting
3622 //if (selectResult2 > 0)
3623 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3626 #ifdef _POSIX_PRIORITY_SCHEDULING
3631 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3633 log(DEBUG,"Reading fd %d",count2a->second->fd);
3634 memset(data, 0, 10240);
3635 result = read(count2a->second->fd, data, 10240);
3640 log(DEBUG,"Read %d characters from socket",result);
3641 userrec* current = count2a->second;
3642 int currfd = current->fd;
3643 char* l = strtok(data,"\n");
3648 if ((floodlines > current->flood) && (current->flood != 0))
3650 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3651 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3652 kill_link(current,"Excess flood");
3655 char sanitized[NetBufferSize];
3656 memset(sanitized, 0, NetBufferSize);
3658 for (int pt = 0; pt < strlen(l); pt++)
3662 sanitized[ptt++] = l[pt];
3665 sanitized[ptt] = '\0';
3666 if (strlen(sanitized))
3670 // we're gonna re-scan to check if the nick is gone, after every
3671 // command - if it has, we're gonna bail
3672 bool find_again = false;
3673 process_buffer(sanitized,current);
3675 // look for the user's record in case it's changed
3676 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3678 if (c2->second->fd == currfd)
3680 // found again, update pointer
3681 current == c2->second;
3690 l = strtok(NULL,"\n");
3695 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3697 log(DEBUG,"killing: %s",count2a->second->nick);
3698 kill_link(count2a->second,strerror(errno));
3702 // result EAGAIN means nothing read
3703 if (result == EAGAIN)
3711 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3712 kill_link(count2a->second,"Client exited");
3713 // must bail here? kill_link removes the hash, corrupting the iterator
3714 log(DEBUG,"Bailing from client exit");
3718 else if (result > 0)
3723 for (int q = 0; q < total_in_this_set; q++)
3725 // there is no iterator += operator :(
3726 //if (count2 != clientlist.end())
3733 // set up select call
3734 for (count = 0; count < boundPortCount; count++)
3736 FD_SET (openSockfd[count], &selectFds);
3740 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3742 /* select is reporting a waiting socket. Poll them all to find out which */
3743 if (selectResult > 0)
3745 char target[MAXBUF], resolved[MAXBUF];
3746 for (count = 0; count < boundPortCount; count++)
3748 if (FD_ISSET (openSockfd[count], &selectFds))
3750 length = sizeof (client);
3751 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3753 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3754 strlcpy (resolved, target, MAXBUF);
3756 if (incomingSockfd < 0)
3758 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3759 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3763 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3764 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3771 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3774 close (incomingSockfd);