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::vector<userrec*> pending_connects;
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(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();
1938 void kill_link_silent(userrec *user,const char* r)
1940 user_hash::iterator iter = clientlist.find(user->nick);
1942 char reason[MAXBUF];
1944 strncpy(reason,r,MAXBUF);
1946 if (strlen(reason)>MAXQUIT)
1948 reason[MAXQUIT-1] = '\0';
1951 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1952 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1953 log(DEBUG,"closing fd %d",user->fd);
1955 /* bugfix, cant close() a nonblocking socket (sux!) */
1956 if (user->registered == 7) {
1957 FOREACH_MOD OnUserQuit(user);
1958 WriteCommonExcept(user,"QUIT :%s",reason);
1960 // Q token must go to ALL servers!!!
1961 char buffer[MAXBUF];
1962 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1963 NetSendToAll(buffer);
1966 /* push the socket on a stack of sockets due to be closed at the next opportunity
1967 * 'Client exited' is an exception to this as it means the client side has already
1968 * closed the socket, we don't need to do it.
1970 fd_reap.push_back(user->fd);
1972 bool do_purge = false;
1974 if (iter != clientlist.end())
1976 log(DEBUG,"deleting user hash value %d",iter->second);
1977 if ((iter->second) && (user->registered == 7)) {
1978 if (iter->second) delete iter->second;
1980 clientlist.erase(iter);
1983 if (user->registered == 7) {
1984 purge_empty_chans();
1990 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1992 char* Passwd(userrec *user)
1994 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1996 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2004 bool IsDenied(userrec *user)
2006 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2008 if (match(user->host,i->host) && (i->type == CC_DENY))
2019 /* sends out an error notice to all connected clients (not to be used
2022 void send_error(char *s)
2024 log(DEBUG,"send_error: %s",s);
2025 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2027 if (isnick(i->second->nick))
2029 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2033 // fix - unregistered connections receive ERROR, not NOTICE
2034 Write(i->second->fd,"ERROR :%s",s);
2039 void Error(int status)
2041 signal (SIGALRM, SIG_IGN);
2042 signal (SIGPIPE, SIG_IGN);
2043 signal (SIGTERM, SIG_IGN);
2044 signal (SIGABRT, SIG_IGN);
2045 signal (SIGSEGV, SIG_IGN);
2046 signal (SIGURG, SIG_IGN);
2047 signal (SIGKILL, SIG_IGN);
2048 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2049 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2054 int main(int argc, char **argv)
2058 log(DEBUG,"*** InspIRCd starting up!");
2059 if (!FileExists(CONFIG_FILE))
2061 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2062 log(DEBUG,"main: no config");
2063 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2067 for (int i = 1; i < argc; i++)
2069 if (!strcmp(argv[i],"-nofork")) {
2072 if (!strcmp(argv[i],"-wait")) {
2077 strlcpy(MyExecutable,argv[0],MAXBUF);
2079 if (InspIRCd() == ERROR)
2081 log(DEBUG,"main: daemon function bailed");
2082 printf("ERROR: could not initialise. Shutting down.\n");
2089 template<typename T> inline string ConvToStr(const T &in)
2092 if (!(tmp << in)) return string();
2096 /* re-allocates a nick in the user_hash after they change nicknames,
2097 * returns a pointer to the new user as it may have moved */
2099 userrec* ReHashNick(char* Old, char* New)
2101 user_hash::iterator newnick;
2102 user_hash::iterator oldnick = clientlist.find(Old);
2104 log(DEBUG,"ReHashNick: %s %s",Old,New);
2106 if (!strcasecmp(Old,New))
2108 log(DEBUG,"old nick is new nick, skipping");
2109 return oldnick->second;
2112 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2114 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2116 clientlist[New] = new userrec();
2117 clientlist[New] = oldnick->second;
2118 clientlist.erase(oldnick);
2120 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2122 return clientlist[New];
2125 /* adds or updates an entry in the whowas list */
2126 void AddWhoWas(userrec* u)
2128 user_hash::iterator iter = whowas.find(u->nick);
2129 userrec *a = new userrec();
2130 strlcpy(a->nick,u->nick,NICKMAX);
2131 strlcpy(a->ident,u->ident,64);
2132 strlcpy(a->dhost,u->dhost,256);
2133 strlcpy(a->host,u->host,256);
2134 strlcpy(a->fullname,u->fullname,128);
2135 strlcpy(a->server,u->server,256);
2136 a->signon = u->signon;
2138 /* MAX_WHOWAS: max number of /WHOWAS items
2139 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2140 * can be replaced by a newer one
2143 if (iter == whowas.end())
2145 if (whowas.size() == WHOWAS_MAX)
2147 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2149 // 3600 seconds in an hour ;)
2150 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2152 if (i->second) delete i->second;
2154 log(DEBUG,"added WHOWAS entry, purged an old record");
2161 log(DEBUG,"added fresh WHOWAS entry");
2162 whowas[a->nick] = a;
2167 log(DEBUG,"updated WHOWAS entry");
2168 if (iter->second) delete iter->second;
2174 /* add a client connection to the sockets list */
2175 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2179 char resolved[MAXBUF];
2182 user_hash::iterator iter;
2184 tempnick = ConvToStr(socket) + "-unknown";
2185 sprintf(tn2,"%d-unknown",socket);
2187 iter = clientlist.find(tempnick);
2189 if (iter != clientlist.end()) return;
2192 * It is OK to access the value here this way since we know
2193 * it exists, we just created it above.
2195 * At NO other time should you access a value in a map or a
2196 * hash_map this way.
2198 clientlist[tempnick] = new userrec();
2200 NonBlocking(socket);
2201 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2203 clientlist[tempnick]->fd = socket;
2204 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2205 strncpy(clientlist[tempnick]->host, host,160);
2206 strncpy(clientlist[tempnick]->dhost, host,160);
2207 strncpy(clientlist[tempnick]->server, ServerName,256);
2208 strncpy(clientlist[tempnick]->ident, "unknown",9);
2209 clientlist[tempnick]->registered = 0;
2210 clientlist[tempnick]->signon = time(NULL);
2211 clientlist[tempnick]->nping = time(NULL)+240;
2212 clientlist[tempnick]->lastping = 1;
2213 clientlist[tempnick]->port = port;
2214 strncpy(clientlist[tempnick]->ip,ip,32);
2216 lookup_dns(clientlist[tempnick]);
2218 // set the registration timeout for this user
2219 unsigned long class_regtimeout = 90;
2220 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2222 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2224 class_regtimeout = (unsigned long)i->registration_timeout;
2229 int class_flood = 0;
2230 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2232 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2234 class_flood = i->flood;
2239 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2240 clientlist[tempnick]->flood = class_flood;
2242 for (int i = 0; i < MAXCHANS; i++)
2244 clientlist[tempnick]->chans[i].channel = NULL;
2245 clientlist[tempnick]->chans[i].uc_modes = 0;
2248 if (clientlist.size() == MAXCLIENTS)
2249 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2251 char* r = matches_zline(ip);
2254 char reason[MAXBUF];
2255 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2256 kill_link(clientlist[tempnick],reason);
2263 return clientlist.size();
2267 int usercount_invisible(void)
2271 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2273 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2278 int usercount_opers(void)
2282 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2284 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2289 int usercount_unknown(void)
2293 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2295 if ((i->second->fd) && (i->second->registered != 7))
2301 long chancount(void)
2303 return chanlist.size();
2306 long count_servs(void)
2309 //for (int j = 0; j < 255; j++)
2311 // if (servers[j] != NULL)
2317 long servercount(void)
2319 return count_servs()+1;
2325 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2327 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2333 void ShowMOTD(userrec *user)
2337 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2340 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2341 for (int i = 0; i != MOTD.size(); i++)
2343 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2345 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2348 void ShowRULES(userrec *user)
2352 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2355 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2356 for (int i = 0; i != RULES.size(); i++)
2358 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2360 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2363 /* shows the message of the day, and any other on-logon stuff */
2364 void FullConnectUser(userrec* user)
2366 user->registered = 7;
2367 user->idle_lastmsg = time(NULL);
2368 log(DEBUG,"ConnectUser: %s",user->nick);
2370 if (strcmp(Passwd(user),"") && (!user->haspassed))
2372 kill_link(user,"Invalid password");
2377 kill_link(user,"Unauthorised connection");
2381 char match_against[MAXBUF];
2382 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2383 char* r = matches_gline(match_against);
2386 char reason[MAXBUF];
2387 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2388 kill_link_silent(user,reason);
2392 r = matches_kline(user->host);
2395 char reason[MAXBUF];
2396 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2397 kill_link_silent(user,reason);
2401 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2402 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2403 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2404 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2405 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2406 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2407 std::stringstream v;
2408 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2409 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2410 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2411 v << std::string(Network);
2412 std::string data005 = v.str();
2413 FOREACH_MOD On005Numeric(data005);
2414 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2415 // so i'd better split it :)
2416 std::stringstream out(data005);
2417 std::string token = "";
2418 std::string line5 = "";
2419 int token_counter = 0;
2423 line5 = line5 + token + " ";
2425 if ((token_counter >= 13) || (out.eof() == true))
2427 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2433 FOREACH_MOD OnUserConnect(user);
2434 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2436 char buffer[MAXBUF];
2437 snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2438 NetSendToAll(buffer);
2441 // handles any connects where DNS isnt done yet, times out stale dns queries on users, and lets completed queries connect.
2442 void HandlePendingConnects()
2444 if (pending_connects.size())
2446 for (std::vector<userrec*>::iterator i = pending_connects.begin(); i <= pending_connects.end(); i++)
2451 // this user's dns is done now.
2452 if ((a->dns_done) && (a->registered == 3))
2454 FullConnectUser(a); // attack! attack!....
2455 pending_connects.erase(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.erase(i);
2469 pending_connects.erase(i);
2476 /* shows the message of the day, and any other on-logon stuff */
2477 void ConnectUser(userrec *user)
2479 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2482 FullConnectUser(user);
2486 // add them to the pending queue
2487 pending_connects.push_back(user);
2491 void handle_version(char **parameters, int pcnt, userrec *user)
2493 char Revision[] = "$Revision$";
2495 char *s1 = Revision;
2497 char *v1 = strtok_r(s1," ",&savept);
2499 char *v2 = strtok_r(s1," ",&savept);
2502 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2506 // calls a handler function for a command
2508 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2510 for (int i = 0; i < cmdlist.size(); i++)
2512 if (!strcasecmp(cmdlist[i].command,commandname))
2514 if (cmdlist[i].handler_function)
2516 if (pcnt>=cmdlist[i].min_params)
2518 if (strchr(user->modes,cmdlist[i].flags_needed))
2520 cmdlist[i].handler_function(parameters,pcnt,user);
2528 void DoSplitEveryone()
2530 bool go_again = true;
2534 for (int i = 0; i < 32; i++)
2538 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2540 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2543 j->CloseConnection();
2544 me[i]->connectors.erase(j);
2552 log(DEBUG,"Removed server. Will remove clients...");
2553 // iterate through the userlist and remove all users on this server.
2554 // because we're dealing with a mesh, we dont have to deal with anything
2555 // "down-route" from this server (nice huh)
2557 char reason[MAXBUF];
2561 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2563 if (strcasecmp(u->second->server,ServerName))
2565 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2566 kill_link(u->second,reason);
2576 char islast(const char* s)
2579 for (int j = 0; j < 32; j++)
2583 for (int k = 0; k < me[j]->connectors.size(); k++)
2585 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2589 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2599 long map_count(const char* s)
2602 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2604 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2610 void force_nickchange(userrec* user,const char* newnick)
2617 FOREACH_RESULT(OnUserPreNick(user,newnick));
2619 kill_link(user,"Nickname collision");
2622 if (matches_qline(newnick))
2624 kill_link(user,"Nickname collision");
2632 strncpy(nick,newnick,MAXBUF);
2634 if (user->registered == 7)
2638 handle_nick(pars,1,user);
2644 int process_parameters(char **command_p,char *parameters)
2649 q = strlen(parameters);
2652 /* no parameters, command_p invalid! */
2655 if (parameters[0] == ':')
2657 command_p[0] = parameters+1;
2662 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2664 /* only one parameter */
2665 command_p[0] = parameters;
2666 if (parameters[0] == ':')
2668 if (strchr(parameters,' ') != NULL)
2676 command_p[j++] = parameters;
2677 for (int i = 0; i <= q; i++)
2679 if (parameters[i] == ' ')
2681 command_p[j++] = parameters+i+1;
2682 parameters[i] = '\0';
2683 if (command_p[j-1][0] == ':')
2685 *command_p[j-1]++; /* remove dodgy ":" */
2687 /* parameter like this marks end of the sequence */
2691 return j; /* returns total number of items in the list */
2694 void process_command(userrec *user, char* cmd)
2698 char *command_p[127];
2699 char p[MAXBUF], temp[MAXBUF];
2700 int i, j, items, cmd_found;
2702 for (int i = 0; i < 127; i++)
2703 command_p[i] = NULL;
2713 if (!strcmp(cmd,""))
2718 int total_params = 0;
2721 for (int q = 0; q < strlen(cmd)-1; q++)
2723 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2726 // found a 'trailing', we dont count them after this.
2734 // another phidjit bug...
2735 if (total_params > 126)
2737 //kill_link(user,"Protocol violation (1)");
2738 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2742 strlcpy(temp,cmd,MAXBUF);
2744 std::string tmp = cmd;
2745 for (int i = 0; i <= MODCOUNT; i++)
2747 std::string oldtmp = tmp;
2748 modules[i]->OnServerRaw(tmp,true,user);
2751 log(DEBUG,"A Module changed the input string!");
2752 log(DEBUG,"New string: %s",tmp.c_str());
2753 log(DEBUG,"Old string: %s",oldtmp.c_str());
2757 strlcpy(cmd,tmp.c_str(),MAXBUF);
2758 strlcpy(temp,cmd,MAXBUF);
2760 if (!strchr(cmd,' '))
2762 /* no parameters, lets skip the formalities and not chop up
2764 log(DEBUG,"About to preprocess command with no params");
2766 command_p[0] = NULL;
2768 for (int i = 0; i <= strlen(cmd); i++)
2770 cmd[i] = toupper(cmd[i]);
2772 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2779 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2780 for (int i = 0; i < strlen(temp); i++)
2782 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2788 /* split the full string into a command plus parameters */
2792 if (strchr(cmd,' '))
2794 for (int i = 0; i <= strlen(cmd); i++)
2796 /* capitalise the command ONLY, leave params intact */
2797 cmd[i] = toupper(cmd[i]);
2798 /* are we nearly there yet?! :P */
2802 parameters = cmd+i+1;
2810 for (int i = 0; i <= strlen(cmd); i++)
2812 cmd[i] = toupper(cmd[i]);
2819 if (strlen(command)>MAXCOMMAND)
2821 //kill_link(user,"Protocol violation (2)");
2822 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2826 for (int x = 0; x < strlen(command); x++)
2828 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2830 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2832 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2834 //kill_link(user,"Protocol violation (3)");
2835 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2842 for (int i = 0; i != cmdlist.size(); i++)
2844 if (strcmp(cmdlist[i].command,""))
2846 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2848 log(DEBUG,"Found matching command");
2852 if (strcmp(parameters,""))
2854 items = process_parameters(command_p,parameters);
2859 command_p[0] = NULL;
2865 command_p[0] = NULL;
2870 log(DEBUG,"Processing command");
2872 /* activity resets the ping pending timer */
2873 user->nping = time(NULL) + 120;
2874 if ((items) < cmdlist[i].min_params)
2876 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2877 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2880 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2882 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2883 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2887 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2889 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2890 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2894 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2896 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2898 if ((!isnick(user->nick)) || (user->registered != 7))
2900 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2901 WriteServ(user->fd,"451 %s :You have not registered",command);
2905 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2907 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2908 if (cmdlist[i].handler_function)
2910 /* ikky /stats counters */
2915 user->bytes_in += strlen(temp);
2918 cmdlist[i].use_count++;
2919 cmdlist[i].total_bytes+=strlen(temp);
2922 /* WARNING: nothing may come after the
2923 * command handler call, as the handler
2924 * may free the user structure! */
2926 cmdlist[i].handler_function(command_p,items,user);
2932 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2933 WriteServ(user->fd,"451 %s :You have not registered",command);
2941 if ((!cmd_found) && (user))
2943 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2944 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2949 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2952 /* create the command and push it onto the table */
2953 strlcpy(comm.command,cmd,MAXBUF);
2954 comm.handler_function = f;
2955 comm.flags_needed = flags;
2956 comm.min_params = minparams;
2958 comm.total_bytes = 0;
2959 cmdlist.push_back(comm);
2960 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2963 void SetupCommandTable(void)
2965 createcommand("USER",handle_user,0,4);
2966 createcommand("NICK",handle_nick,0,1);
2967 createcommand("QUIT",handle_quit,0,0);
2968 createcommand("VERSION",handle_version,0,0);
2969 createcommand("PING",handle_ping,0,1);
2970 createcommand("PONG",handle_pong,0,1);
2971 createcommand("ADMIN",handle_admin,0,0);
2972 createcommand("PRIVMSG",handle_privmsg,0,2);
2973 createcommand("INFO",handle_info,0,0);
2974 createcommand("TIME",handle_time,0,0);
2975 createcommand("WHOIS",handle_whois,0,1);
2976 createcommand("WALLOPS",handle_wallops,'o',1);
2977 createcommand("NOTICE",handle_notice,0,2);
2978 createcommand("JOIN",handle_join,0,1);
2979 createcommand("NAMES",handle_names,0,1);
2980 createcommand("PART",handle_part,0,1);
2981 createcommand("KICK",handle_kick,0,2);
2982 createcommand("MODE",handle_mode,0,1);
2983 createcommand("TOPIC",handle_topic,0,1);
2984 createcommand("WHO",handle_who,0,1);
2985 createcommand("MOTD",handle_motd,0,0);
2986 createcommand("RULES",handle_rules,0,0);
2987 createcommand("OPER",handle_oper,0,2);
2988 createcommand("LIST",handle_list,0,0);
2989 createcommand("DIE",handle_die,'o',1);
2990 createcommand("RESTART",handle_restart,'o',1);
2991 createcommand("KILL",handle_kill,'o',2);
2992 createcommand("REHASH",handle_rehash,'o',0);
2993 createcommand("LUSERS",handle_lusers,0,0);
2994 createcommand("STATS",handle_stats,0,1);
2995 createcommand("USERHOST",handle_userhost,0,1);
2996 createcommand("AWAY",handle_away,0,0);
2997 createcommand("ISON",handle_ison,0,0);
2998 createcommand("SUMMON",handle_summon,0,0);
2999 createcommand("USERS",handle_users,0,0);
3000 createcommand("INVITE",handle_invite,0,2);
3001 createcommand("PASS",handle_pass,0,1);
3002 createcommand("TRACE",handle_trace,'o',0);
3003 createcommand("WHOWAS",handle_whowas,0,1);
3004 createcommand("CONNECT",handle_connect,'o',1);
3005 createcommand("SQUIT",handle_squit,'o',0);
3006 createcommand("MODULES",handle_modules,'o',0);
3007 createcommand("LINKS",handle_links,0,0);
3008 createcommand("MAP",handle_map,0,0);
3009 createcommand("KLINE",handle_kline,'o',1);
3010 createcommand("GLINE",handle_gline,'o',1);
3011 createcommand("ZLINE",handle_zline,'o',1);
3012 createcommand("QLINE",handle_qline,'o',1);
3013 createcommand("SERVER",handle_server,0,0);
3016 void process_buffer(const char* cmdbuf,userrec *user)
3020 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3027 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3030 if (!strcmp(cmdbuf,""))
3034 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3036 strlcpy(cmd,cmdbuf,MAXBUF);
3037 if (!strcmp(cmd,""))
3041 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3043 cmd[strlen(cmd)-1] = '\0';
3045 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3047 cmd[strlen(cmd)-1] = '\0';
3050 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3052 cmd[strlen(cmd)-1] = '\0';
3055 if (!strcmp(cmd,""))
3059 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3061 if ((user) && (cmd))
3063 process_command(user,cmd);
3067 void DoSync(serverrec* serv, char* tcp_host)
3070 log(DEBUG,"Sending sync");
3071 // send start of sync marker: Y <timestamp>
3072 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3073 // except the ones its receiving it from.
3074 snprintf(data,MAXBUF,"Y %d",time(NULL));
3075 serv->SendPacket(data,tcp_host);
3076 // send users and channels
3077 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3079 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);
3080 serv->SendPacket(data,tcp_host);
3081 if (strchr(u->second->modes,'o'))
3083 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3084 serv->SendPacket(data,tcp_host);
3086 for (int i = 0; i <= MODCOUNT; i++)
3088 string_list l = modules[i]->OnUserSync(u->second);
3089 for (int j = 0; j < l.size(); j++)
3091 strlcpy(data,l[j].c_str(),MAXBUF);
3092 serv->SendPacket(data,tcp_host);
3095 if (strcmp(chlist(u->second),""))
3097 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3098 serv->SendPacket(data,tcp_host);
3101 // send channel modes, topics etc...
3102 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3104 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3105 serv->SendPacket(data,tcp_host);
3106 for (int i = 0; i <= MODCOUNT; i++)
3108 string_list l = modules[i]->OnChannelSync(c->second);
3109 for (int j = 0; j < l.size(); j++)
3111 strlcpy(data,l[j].c_str(),MAXBUF);
3112 serv->SendPacket(data,tcp_host);
3115 if (strcmp(c->second->topic,""))
3117 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3118 serv->SendPacket(data,tcp_host);
3120 // send current banlist
3122 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3124 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3125 serv->SendPacket(data,tcp_host);
3128 // sync global zlines, glines, etc
3129 sync_xlines(serv,tcp_host);
3131 for (int j = 0; j < 32; j++)
3135 for (int k = 0; k < me[j]->connectors.size(); k++)
3137 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3139 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3140 serv->SendPacket(data,tcp_host);
3141 NetSendMyRoutingTable();
3147 snprintf(data,MAXBUF,"F %d",time(NULL));
3148 serv->SendPacket(data,tcp_host);
3149 log(DEBUG,"Sent sync");
3150 // ircd sends its serverlist after the end of sync here
3154 void NetSendMyRoutingTable()
3156 // send out a line saying what is reachable to us.
3157 // E.g. if A is linked to B C and D, send out:
3159 // if its only linked to B and D send out:
3161 // if it has no links, dont even send out the line at all.
3162 char buffer[MAXBUF];
3163 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3164 bool sendit = false;
3165 for (int i = 0; i < 32; i++)
3169 for (int j = 0; j < me[i]->connectors.size(); j++)
3171 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3173 strlcat(buffer," ",MAXBUF);
3174 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3181 NetSendToAll(buffer);
3185 void DoSplit(const char* params)
3187 bool go_again = true;
3191 for (int i = 0; i < 32; i++)
3195 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3197 if (!strcasecmp(j->GetServerName().c_str(),params))
3200 j->CloseConnection();
3201 me[i]->connectors.erase(j);
3209 log(DEBUG,"Removed server. Will remove clients...");
3210 // iterate through the userlist and remove all users on this server.
3211 // because we're dealing with a mesh, we dont have to deal with anything
3212 // "down-route" from this server (nice huh)
3214 char reason[MAXBUF];
3215 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3219 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3221 if (!strcasecmp(u->second->server,params))
3223 kill_link(u->second,reason);
3231 // removes a server. Will NOT remove its users!
3233 void RemoveServer(const char* name)
3235 bool go_again = true;
3239 for (int i = 0; i < 32; i++)
3243 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3245 if (!strcasecmp(j->GetServerName().c_str(),name))
3248 j->CloseConnection();
3249 me[i]->connectors.erase(j);
3260 int reap_counter = 0;
3264 struct sockaddr_in client,server;
3265 char addrs[MAXBUF][255];
3266 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3269 int selectResult = 0, selectResult2 = 0;
3270 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3271 char resolvedHost[MAXBUF];
3275 log_file = fopen("ircd.log","a+");
3278 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3282 log(DEBUG,"InspIRCd: startup: begin");
3286 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3288 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3290 SetupCommandTable();
3291 log(DEBUG,"InspIRCd: startup: default command table set up");
3293 ReadConfig(true,NULL);
3294 if (strcmp(DieValue,""))
3296 printf("WARNING: %s\n\n",DieValue);
3299 log(DEBUG,"InspIRCd: startup: read config");
3301 int count2 = 0, count3 = 0;
3303 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3305 ConfValue("bind","port",count,configToken,&config_f);
3306 ConfValue("bind","address",count,Addr,&config_f);
3307 ConfValue("bind","type",count,Type,&config_f);
3308 if (!strcmp(Type,"servers"))
3310 char Default[MAXBUF];
3311 strcpy(Default,"no");
3312 ConfValue("bind","default",count,Default,&config_f);
3313 if (strchr(Default,'y'))
3315 defaultRoute = count3;
3316 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3318 me[count3] = new serverrec(ServerName,100L,false);
3319 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3321 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3330 ports[count2] = atoi(configToken);
3331 strlcpy(addrs[count2],Addr,256);
3334 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3337 UDPportCount = count3;
3339 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3341 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3345 /* BugFix By Craig! :p */
3347 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3349 char modfile[MAXBUF];
3350 ConfValue("module","name",count2,configToken,&config_f);
3351 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3352 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3353 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3354 /* If The File Doesnt exist, Trying to load it
3355 * Will Segfault the IRCd.. So, check to see if
3356 * it Exists, Before Proceeding. */
3357 if (FileExists(modfile))
3359 factory[count] = new ircd_module(modfile);
3360 if (factory[count]->LastError())
3362 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3363 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3366 if (factory[count]->factory)
3368 modules[count] = factory[count]->factory->CreateModule();
3369 /* save the module and the module's classfactory, if
3370 * this isnt done, random crashes can occur :/ */
3371 module_names.push_back(modfile);
3375 log(DEBUG,"Unable to load %s",modfile);
3376 printf("Unable to load %s\nExiting...\n",modfile);
3379 /* Increase the Count */
3384 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3385 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3388 MODCOUNT = count - 1;
3389 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3391 printf("\nInspIRCd is now running!\n");
3393 startup_time = time(NULL);
3397 log(VERBOSE,"Not forking as -nofork was specified");
3401 if (DaemonSeed() == ERROR)
3403 log(DEBUG,"InspIRCd: startup: can't daemonise");
3404 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3410 /* setup select call */
3411 FD_ZERO(&selectFds);
3412 log(DEBUG,"InspIRCd: startup: zero selects");
3413 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3415 for (count = 0; count < portCount; count++)
3417 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3419 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3422 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3424 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3426 else /* well we at least bound to one socket so we'll continue */
3432 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3434 /* if we didn't bind to anything then abort */
3435 if (boundPortCount == 0)
3437 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3442 length = sizeof (client);
3443 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3445 /* main loop, this never returns */
3448 #ifdef _POSIX_PRIORITY_SCHEDULING
3451 // update the status of klines, etc
3461 // handle pending connects
3462 HandlePendingConnects();
3464 user_hash::iterator count2 = clientlist.begin();
3466 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3467 // them in a list, then reap the list every second or so.
3468 if (reap_counter>300)
3470 if (fd_reap.size() > 0)
3472 for( int n = 0; n < fd_reap.size(); n++)
3474 Blocking(fd_reap[n]);
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);