1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
46 #include "connection.h"
58 #include "inspstring.h"
62 #define nspace __gnu_cxx
67 int LogLevel = DEFAULT;
68 char ServerName[MAXBUF];
70 char ServerDesc[MAXBUF];
71 char AdminName[MAXBUF];
72 char AdminEmail[MAXBUF];
73 char AdminNick[MAXBUF];
75 char restartpass[MAXBUF];
79 char PrefixQuit[MAXBUF];
80 char DieValue[MAXBUF];
81 char DNSServer[MAXBUF];
83 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
84 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
86 time_t startup_time = time(NULL);
87 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
88 extern int MaxWhoResults;
92 bool AllowHalfop = true;
93 bool AllowProtect = true;
94 bool AllowFounder = true;
96 extern std::vector<Module*> modules;
97 std::vector<std::string> module_names;
98 extern std::vector<ircd_module*> factory;
99 std::vector<int> fd_reap;
102 int openSockfd[MAXSOCKS];
105 time_t TIME = time(NULL);
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 char* Passwd(userrec *user);
205 bool IsDenied(userrec *user);
206 void AddWhoWas(userrec* u);
208 std::vector<long> auth_cookies;
209 std::stringstream config_f(stringstream::in | stringstream::out);
215 char Revision[] = "$Revision$";
218 char *v1 = strtok_r(s1," ",&savept);
220 char *v2 = strtok_r(s1," ",&savept);
222 return (long)(atof(v2)*10000);
226 std::string getservername()
231 std::string getserverdesc()
236 std::string getnetworkname()
241 std::string getadminname()
246 std::string getadminemail()
251 std::string getadminnick()
256 void log(int level,char *text, ...)
258 char textbuffer[MAXBUF];
261 struct tm * timeinfo;
262 if (level < LogLevel)
266 timeinfo = localtime (&rawtime);
271 va_start (argsPtr, text);
272 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
274 strlcpy(b,asctime(timeinfo),MAXBUF);
275 b[strlen(b)-1] = ':';
276 fprintf(log_file,"%s %s\n",b,textbuffer);
279 // nofork enabled? display it on terminal too
280 printf("%s %s\n",b,textbuffer);
285 void readfile(file_cache &F, const char* fname)
288 char linebuf[MAXBUF];
290 log(DEBUG,"readfile: loading %s",fname);
292 file = fopen(fname,"r");
297 fgets(linebuf,sizeof(linebuf),file);
298 linebuf[strlen(linebuf)-1]='\0';
299 if (!strcmp(linebuf,""))
305 F.push_back(linebuf);
312 log(DEBUG,"readfile: failed to load file: %s",fname);
314 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
317 void ReadConfig(bool bail, userrec* user)
319 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
320 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF];
322 std::stringstream errstr;
324 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
329 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
337 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
338 while (!errstr.eof())
340 errstr.getline(dataline,1024);
341 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
346 WriteOpers("There were errors in the configuration file:",user->nick);
347 while (!errstr.eof())
349 errstr.getline(dataline,1024);
350 WriteOpers(dataline);
357 ConfValue("server","name",0,ServerName,&config_f);
358 ConfValue("server","description",0,ServerDesc,&config_f);
359 ConfValue("server","network",0,Network,&config_f);
360 ConfValue("admin","name",0,AdminName,&config_f);
361 ConfValue("admin","email",0,AdminEmail,&config_f);
362 ConfValue("admin","nick",0,AdminNick,&config_f);
363 ConfValue("files","motd",0,motd,&config_f);
364 ConfValue("files","rules",0,rules,&config_f);
365 ConfValue("power","diepass",0,diepass,&config_f);
366 ConfValue("power","pause",0,pauseval,&config_f);
367 ConfValue("power","restartpass",0,restartpass,&config_f);
368 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
369 ConfValue("die","value",0,DieValue,&config_f);
370 ConfValue("options","loglevel",0,dbg,&config_f);
371 ConfValue("options","netbuffersize",0,NB,&config_f);
372 ConfValue("options","maxwho",0,MW,&config_f);
373 ConfValue("options","allowhalfop",0,AH,&config_f);
374 ConfValue("options","allowprotect",0,AP,&config_f);
375 ConfValue("options","allowfounder",0,AF,&config_f);
376 ConfValue("dns","server",0,DNSServer,&config_f);
377 ConfValue("dns","timeout",0,DNT,&config_f);
378 NetBufferSize = atoi(NB);
379 MaxWhoResults = atoi(MW);
380 dns_timeout = atoi(DNT);
383 if (!strcmp(DNSServer,""))
384 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
385 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
386 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
387 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
388 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
390 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
391 NetBufferSize = 10240;
393 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
395 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
398 if (!strcmp(dbg,"debug"))
400 if (!strcmp(dbg,"verbose"))
402 if (!strcmp(dbg,"default"))
404 if (!strcmp(dbg,"sparse"))
406 if (!strcmp(dbg,"none"))
409 log(DEFAULT,"Reading message of the day...");
410 readfile(RULES,rules);
411 log(DEFAULT,"Reading connect classes...");
413 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
416 ConfValue("connect","allow",i,Value,&config_f);
417 ConfValue("connect","timeout",i,timeout,&config_f);
418 ConfValue("connect","flood",i,flood,&config_f);
419 if (strcmp(Value,""))
421 strlcpy(c.host,Value,MAXBUF);
423 strlcpy(Value,"",MAXBUF);
424 ConfValue("connect","password",i,Value,&config_f);
425 strlcpy(c.pass,Value,MAXBUF);
426 c.registration_timeout = 90; // default is 2 minutes
427 c.flood = atoi(flood);
430 c.registration_timeout = atoi(timeout);
432 Classes.push_back(c);
433 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
437 ConfValue("connect","deny",i,Value,&config_f);
438 strlcpy(c.host,Value,MAXBUF);
440 Classes.push_back(c);
441 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
445 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
446 read_xline_defaults();
447 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
449 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
452 /* write formatted text to a socket, in same format as printf */
454 void Write(int sock,char *text, ...)
458 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
461 char textbuffer[MAXBUF];
465 va_start (argsPtr, text);
466 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
468 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
472 write(sock,tb,strlen(tb));
476 /* write a server formatted numeric response to a single socket */
478 void WriteServ(int sock, char* text, ...)
482 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
485 char textbuffer[MAXBUF],tb[MAXBUF];
487 va_start (argsPtr, text);
489 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
491 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
495 write(sock,tb,strlen(tb));
499 /* write text from an originating user to originating user */
501 void WriteFrom(int sock, userrec *user,char* text, ...)
503 if ((!text) || (!user))
505 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
508 char textbuffer[MAXBUF],tb[MAXBUF];
510 va_start (argsPtr, text);
512 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
514 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
518 write(sock,tb,strlen(tb));
522 /* write text to an destination user from a source user (e.g. user privmsg) */
524 void WriteTo(userrec *source, userrec *dest,char *data, ...)
526 if ((!dest) || (!data))
528 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
531 char textbuffer[MAXBUF],tb[MAXBUF];
533 va_start (argsPtr, data);
534 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
538 // if no source given send it from the server.
541 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
545 WriteFrom(dest->fd,source,"%s",textbuffer);
549 /* write formatted text from a source user to all users on a channel
550 * including the sender (NOT for privmsg, notice etc!) */
552 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
554 if ((!Ptr) || (!user) || (!text))
556 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
559 char textbuffer[MAXBUF];
561 va_start (argsPtr, text);
562 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
564 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
566 if (has_channel(i->second,Ptr))
568 WriteTo(user,i->second,"%s",textbuffer);
573 /* write formatted text from a source user to all users on a channel
574 * including the sender (NOT for privmsg, notice etc!) doesnt send to
575 * users on remote servers */
577 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
579 if ((!Ptr) || (!text))
581 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
584 char textbuffer[MAXBUF];
586 va_start (argsPtr, text);
587 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
589 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
591 if (has_channel(i->second,Ptr))
593 if (i->second->fd != -1)
597 WriteServ(i->second->fd,"%s",textbuffer);
601 WriteTo(user,i->second,"%s",textbuffer);
609 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
611 if ((!Ptr) || (!user) || (!text))
613 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
616 char textbuffer[MAXBUF];
618 va_start (argsPtr, text);
619 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
621 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
625 if (has_channel(i->second,Ptr))
627 WriteServ(i->second->fd,"%s",textbuffer);
634 /* write formatted text from a source user to all users on a channel except
635 * for the sender (for privmsg etc) */
637 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
639 if ((!Ptr) || (!user) || (!text))
641 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
644 char textbuffer[MAXBUF];
646 va_start (argsPtr, text);
647 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
650 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
654 if (has_channel(i->second,Ptr) && (user != i->second))
656 WriteTo(user,i->second,"%s",textbuffer);
663 std::string GetServerDescription(char* servername)
665 for (int j = 0; j < 32; j++)
669 for (int k = 0; k < me[j]->connectors.size(); k++)
671 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
673 return me[j]->connectors[k].GetDescription();
677 return ServerDesc; // not a remote server that can be found, it must be me.
682 /* write a formatted string to all users who share at least one common
683 * channel, including the source user e.g. for use in NICK */
685 void WriteCommon(userrec *u, char* text, ...)
689 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
693 if (u->registered != 7) {
694 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
698 char textbuffer[MAXBUF];
700 va_start (argsPtr, text);
701 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
704 WriteFrom(u->fd,u,"%s",textbuffer);
706 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
710 if (common_channels(u,i->second) && (i->second != u))
712 WriteFrom(i->second->fd,u,"%s",textbuffer);
718 /* write a formatted string to all users who share at least one common
719 * channel, NOT including the source user e.g. for use in QUIT */
721 void WriteCommonExcept(userrec *u, char* text, ...)
725 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
729 if (u->registered != 7) {
730 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
734 char textbuffer[MAXBUF];
736 va_start (argsPtr, text);
737 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
740 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
744 if ((common_channels(u,i->second)) && (u != i->second))
746 WriteFrom(i->second->fd,u,"%s",textbuffer);
752 void WriteOpers(char* text, ...)
756 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
760 char textbuffer[MAXBUF];
762 va_start (argsPtr, text);
763 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
766 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
770 if (strchr(i->second->modes,'o'))
772 if (strchr(i->second->modes,'s'))
774 // send server notices to all with +s
775 // (TODO: needs SNOMASKs)
776 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
783 // returns TRUE of any users on channel C occupy server 'servername'.
785 bool ChanAnyOnThisServer(chanrec *c,char* servername)
787 log(DEBUG,"ChanAnyOnThisServer");
788 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
790 if (has_channel(i->second,c))
792 if (!strcasecmp(i->second->server,servername))
801 // returns true if user 'u' shares any common channels with any users on server 'servername'
803 bool CommonOnThisServer(userrec* u,const char* servername)
805 log(DEBUG,"ChanAnyOnThisServer");
806 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
808 if ((common_channels(u,i->second)) && (u != i->second))
810 if (!strcasecmp(i->second->server,servername))
812 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
821 void NetSendToCommon(userrec* u, char* s)
824 snprintf(buffer,MAXBUF,"%s",s);
826 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
828 for (int j = 0; j < 32; j++)
832 for (int k = 0; k < me[j]->connectors.size(); k++)
834 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
836 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
844 void NetSendToAll(char* s)
847 snprintf(buffer,MAXBUF,"%s",s);
849 log(DEBUG,"NetSendToAll: '%s'",s);
851 for (int j = 0; j < 32; j++)
855 for (int k = 0; k < me[j]->connectors.size(); k++)
857 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
863 void NetSendToAllAlive(char* s)
866 snprintf(buffer,MAXBUF,"%s",s);
868 log(DEBUG,"NetSendToAllAlive: '%s'",s);
870 for (int j = 0; j < 32; j++)
874 for (int k = 0; k < me[j]->connectors.size(); k++)
876 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
878 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
882 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
890 void NetSendToOne(char* target,char* s)
893 snprintf(buffer,MAXBUF,"%s",s);
895 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
897 for (int j = 0; j < 32; j++)
901 for (int k = 0; k < me[j]->connectors.size(); k++)
903 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
905 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
912 void NetSendToAllExcept(const char* target,char* s)
915 snprintf(buffer,MAXBUF,"%s",s);
917 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
919 for (int j = 0; j < 32; j++)
923 for (int k = 0; k < me[j]->connectors.size(); k++)
925 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
927 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
935 void WriteMode(const char* modes, int flags, const char* text, ...)
937 if ((!text) || (!modes) || (!flags))
939 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
943 char textbuffer[MAXBUF];
945 va_start (argsPtr, text);
946 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
949 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
953 bool send_to_user = false;
958 for (int n = 0; n < strlen(modes); n++)
960 if (!hasumode(i->second,modes[n]))
962 send_to_user = false;
967 else if (flags == WM_OR)
969 send_to_user = false;
970 for (int n = 0; n < strlen(modes); n++)
972 if (hasumode(i->second,modes[n]))
982 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
989 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
991 if ((!text) || (!source))
993 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
998 char textbuffer[MAXBUF];
1000 va_start (argsPtr, text);
1001 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1004 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1008 if (strchr(i->second->modes,'w'))
1010 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1017 char buffer[MAXBUF];
1018 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1019 NetSendToAll(buffer);
1023 /* convert a string to lowercase. Note following special circumstances
1024 * taken from RFC 1459. Many "official" server branches still hold to this
1025 * rule so i will too;
1027 * Because of IRC's scandanavian origin, the characters {}| are
1028 * considered to be the lower case equivalents of the characters []\,
1029 * respectively. This is a critical issue when determining the
1030 * equivalence of two nicknames.
1033 void strlower(char *n)
1039 for (int i = 0; i != strlen(n); i++)
1041 n[i] = tolower(n[i]);
1053 /* Find a user record by nickname and return a pointer to it */
1055 userrec* Find(std::string nick)
1057 user_hash::iterator iter = clientlist.find(nick);
1059 if (iter == clientlist.end())
1060 /* Couldn't find it */
1063 return iter->second;
1066 /* find a channel record by channel name and return a pointer to it */
1068 chanrec* FindChan(const char* chan)
1072 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1076 chan_hash::iterator iter = chanlist.find(chan);
1078 if (iter == chanlist.end())
1079 /* Couldn't find it */
1082 return iter->second;
1086 long GetMaxBans(char* name)
1089 for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1091 ConfValue("banlist","chan",count,CM,&config_f);
1094 ConfValue("banlist","limit",count,CM,&config_f);
1102 void purge_empty_chans(void)
1104 int go_again = 1, purge = 0;
1109 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1112 if (!usercount(i->second))
1114 /* kill the record */
1115 if (i != chanlist.end())
1117 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1118 if (i->second) delete i->second;
1127 log(DEBUG,"skipped purge for %s",i->second->name);
1132 log(DEBUG,"completed channel purge, killed %d",purge);
1136 char scratch[MAXBUF];
1137 char sparam[MAXBUF];
1139 char* chanmodes(chanrec *chan)
1143 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1150 if (chan->noexternal)
1152 strlcat(scratch,"n",MAXMODES);
1154 if (chan->topiclock)
1156 strlcat(scratch,"t",MAXMODES);
1158 if (strcmp(chan->key,""))
1160 strlcat(scratch,"k",MAXMODES);
1164 strlcat(scratch,"l",MAXMODES);
1166 if (chan->inviteonly)
1168 strlcat(scratch,"i",MAXMODES);
1170 if (chan->moderated)
1172 strlcat(scratch,"m",MAXMODES);
1176 strlcat(scratch,"s",MAXMODES);
1178 if (chan->c_private)
1180 strlcat(scratch,"p",MAXMODES);
1182 if (strcmp(chan->key,""))
1184 strlcat(sparam," ",MAXBUF);
1185 strlcat(sparam,chan->key,MAXBUF);
1190 sprintf(foo," %d",chan->limit);
1191 strlcat(sparam,foo,MAXBUF);
1193 if (strlen(chan->custom_modes))
1195 strlcat(scratch,chan->custom_modes,MAXMODES);
1196 for (int z = 0; z < strlen(chan->custom_modes); z++)
1198 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1201 strlcat(sparam," ",MAXBUF);
1202 strlcat(sparam,extparam.c_str(),MAXBUF);
1206 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1207 strlcat(scratch,sparam,MAXMODES);
1212 /* compile a userlist of a channel into a string, each nick seperated by
1213 * spaces and op, voice etc status shown as @ and + */
1215 void userlist(userrec *user,chanrec *c)
1217 if ((!c) || (!user))
1219 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1223 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1224 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1226 if (has_channel(i->second,c))
1228 if (isnick(i->second->nick))
1230 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1232 /* user is +i, and source not on the channel, does not show
1233 * nick in NAMES list */
1236 strlcat(list,cmode(i->second,c),MAXBUF);
1237 strlcat(list,i->second->nick,MAXBUF);
1238 strlcat(list," ",MAXBUF);
1239 if (strlen(list)>(480-NICKMAX))
1241 /* list overflowed into
1242 * multiple numerics */
1243 WriteServ(user->fd,"%s",list);
1244 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1249 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1251 WriteServ(user->fd,"%s",list);
1255 /* return a count of the users on a specific channel accounting for
1256 * invisible users who won't increase the count. e.g. for /LIST */
1258 int usercount_i(chanrec *c)
1265 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1270 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1274 if (has_channel(i->second,c))
1276 if (isnick(i->second->nick))
1278 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1280 /* user is +i, and source not on the channel, does not show
1281 * nick in NAMES list */
1289 log(DEBUG,"usercount_i: %s %d",c->name,count);
1294 int usercount(chanrec *c)
1301 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1306 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1310 if (has_channel(i->second,c))
1312 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1319 log(DEBUG,"usercount: %s %d",c->name,count);
1324 /* add a channel to a user, creating the record for it if needed and linking
1325 * it to the user record */
1327 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1329 if ((!user) || (!cn))
1331 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1340 strncpy(cname,cn,MAXBUF);
1342 // we MUST declare this wherever we use FOREACH_RESULT
1345 if (strlen(cname) > CHANMAX-1)
1347 cname[CHANMAX-1] = '\0';
1350 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1352 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1354 return NULL; // already on the channel!
1358 if (!FindChan(cname))
1361 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1362 if (MOD_RESULT == 1) {
1366 /* create a new one */
1367 log(DEBUG,"add_channel: creating: %s",cname);
1369 chanlist[cname] = new chanrec();
1371 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1372 chanlist[cname]->topiclock = 1;
1373 chanlist[cname]->noexternal = 1;
1374 chanlist[cname]->created = TIME;
1375 strcpy(chanlist[cname]->topic, "");
1376 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1377 chanlist[cname]->topicset = 0;
1378 Ptr = chanlist[cname];
1379 log(DEBUG,"add_channel: created: %s",cname);
1380 /* set created to 2 to indicate user
1381 * is the first in the channel
1382 * and should be given ops */
1388 /* channel exists, just fish out a pointer to its struct */
1389 Ptr = FindChan(cname);
1392 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1394 // the override flag allows us to bypass channel modes
1395 // and bans (used by servers)
1396 if ((!override) || (!strcasecmp(user->server,ServerName)))
1398 log(DEBUG,"Not overriding...");
1400 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1401 if (MOD_RESULT == 1) {
1404 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1408 log(DEBUG,"add_channel: checking key, invite, etc");
1409 if (strcmp(Ptr->key,""))
1411 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1414 log(DEBUG,"add_channel: no key given in JOIN");
1415 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1420 log(DEBUG,"key at %p is %s",key,key);
1421 if (strcasecmp(key,Ptr->key))
1423 log(DEBUG,"add_channel: bad key given in JOIN");
1424 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1429 log(DEBUG,"add_channel: no key");
1431 if (Ptr->inviteonly)
1433 log(DEBUG,"add_channel: channel is +i");
1434 if (user->IsInvited(Ptr->name))
1436 /* user was invited to channel */
1437 /* there may be an optional channel NOTICE here */
1441 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1445 log(DEBUG,"add_channel: channel is not +i");
1449 if (usercount(Ptr) == Ptr->limit)
1451 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1456 log(DEBUG,"add_channel: about to walk banlist");
1458 /* check user against the channel banlist */
1461 if (Ptr->bans.size())
1463 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1465 if (match(user->GetFullHost(),i->data))
1467 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1474 log(DEBUG,"add_channel: bans checked");
1479 if ((Ptr) && (user))
1481 user->RemoveInvite(Ptr->name);
1484 log(DEBUG,"add_channel: invites removed");
1489 log(DEBUG,"Overridden checks");
1497 log(DEBUG,"Passed channel checks");
1499 for (int i =0; i != MAXCHANS; i++)
1501 log(DEBUG,"Check location %d",i);
1502 if (user->chans[i].channel == NULL)
1504 log(DEBUG,"Adding into their channel list at location %d",i);
1508 /* first user in is given ops */
1509 user->chans[i].uc_modes = UCMODE_OP;
1513 user->chans[i].uc_modes = 0;
1515 user->chans[i].channel = Ptr;
1516 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1518 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1520 // use the stamdard J token with no privilages.
1521 char buffer[MAXBUF];
1524 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1528 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1530 NetSendToAll(buffer);
1533 log(DEBUG,"Sent JOIN to client");
1537 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1538 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1541 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1542 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1543 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1544 FOREACH_MOD OnUserJoin(user,Ptr);
1548 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1549 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1553 /* remove a channel from a users record, and remove the record from memory
1554 * if the channel has become empty */
1556 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1558 if ((!user) || (!cname))
1560 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1567 if ((!cname) || (!user))
1572 Ptr = FindChan(cname);
1579 FOREACH_MOD OnUserPart(user,Ptr);
1580 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1582 for (int i =0; i != MAXCHANS; i++)
1584 /* zap it from the channel list of the user */
1585 if (user->chans[i].channel == Ptr)
1589 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1593 char buffer[MAXBUF];
1594 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1595 NetSendToAll(buffer);
1604 char buffer[MAXBUF];
1605 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1606 NetSendToAll(buffer);
1609 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1611 user->chans[i].uc_modes = 0;
1612 user->chans[i].channel = NULL;
1613 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1618 /* if there are no users left on the channel */
1619 if (!usercount(Ptr))
1621 chan_hash::iterator iter = chanlist.find(Ptr->name);
1623 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1625 /* kill the record */
1626 if (iter != chanlist.end())
1628 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1629 if (iter->second) delete iter->second;
1630 chanlist.erase(iter);
1636 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1638 if ((!src) || (!user) || (!Ptr) || (!reason))
1640 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1647 if ((!Ptr) || (!user) || (!src))
1652 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1654 if (!has_channel(user,Ptr))
1656 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1661 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1663 if (MOD_RESULT == ACR_DENY)
1666 if (MOD_RESULT == ACR_DEFAULT)
1668 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1670 if (cstatus(src,Ptr) == STATUS_HOP)
1672 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1676 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1683 for (int i =0; i != MAXCHANS; i++)
1685 /* zap it from the channel list of the user */
1686 if (user->chans[i].channel)
1687 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1689 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1690 user->chans[i].uc_modes = 0;
1691 user->chans[i].channel = NULL;
1692 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1697 /* if there are no users left on the channel */
1698 if (!usercount(Ptr))
1700 chan_hash::iterator iter = chanlist.find(Ptr->name);
1702 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1704 /* kill the record */
1705 if (iter != chanlist.end())
1707 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1708 if (iter->second) delete iter->second;
1709 chanlist.erase(iter);
1717 /* This function pokes and hacks at a parameter list like the following:
1719 * PART #winbot,#darkgalaxy :m00!
1721 * to turn it into a series of individual calls like this:
1723 * PART #winbot :m00!
1724 * PART #darkgalaxy :m00!
1726 * The seperate calls are sent to a callback function provided by the caller
1727 * (the caller will usually call itself recursively). The callback function
1728 * must be a command handler. Calling this function on a line with no list causes
1729 * no action to be taken. You must provide a starting and ending parameter number
1730 * where the range of the list can be found, useful if you have a terminating
1731 * parameter as above which is actually not part of the list, or parameters
1732 * before the actual list as well. This code is used by many functions which
1733 * can function as "one to list" (see the RFC) */
1735 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1740 char blog[32][MAXBUF];
1741 char blog2[32][MAXBUF];
1742 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1743 char keystr[MAXBUF];
1746 for (int i = 0; i <32; i++)
1749 for (int i = 0; i <32; i++)
1750 strcpy(blog2[i],"");
1753 for (int i = 0; i <10; i++)
1757 parameters[i] = moo;
1762 if (pcnt > 1) /* we have a key to copy */
1764 strlcpy(keystr,parameters[1],MAXBUF);
1768 if (!parameters[start])
1772 if (!strchr(parameters[start],','))
1777 for (int i = start; i <= end; i++)
1781 strlcat(plist,parameters[i],MAXBUF);
1789 for (int i = 0; i < t; i++)
1791 if (plist[i] == ',')
1794 strlcpy(blog[j++],param,MAXBUF);
1798 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1803 strlcpy(blog[j++],param,MAXBUF);
1806 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1811 if ((joins) && (keystr))
1813 if (strchr(keystr,','))
1817 t2 = strlen(keystr);
1818 for (int i = 0; i < t2; i++)
1820 if (keystr[i] == ',')
1823 strlcpy(blog2[j++],param,MAXBUF);
1827 strlcpy(blog2[j++],param,MAXBUF);
1832 for (j = 0; j < total; j++)
1838 for (q = end; q < pcnt-1; q++)
1840 if (parameters[q+1])
1842 pars[q-end+1] = parameters[q+1];
1845 if ((joins) && (parameters[1]))
1856 /* repeatedly call the function with the hacked parameter list */
1857 if ((joins) && (pcnt > 1))
1861 // pars[1] already set up and containing key from blog2[j]
1866 pars[1] = parameters[1];
1872 fn(pars,pcnt-(end-start),u);
1881 void kill_link(userrec *user,const char* r)
1883 user_hash::iterator iter = clientlist.find(user->nick);
1885 char reason[MAXBUF];
1887 strncpy(reason,r,MAXBUF);
1889 if (strlen(reason)>MAXQUIT)
1891 reason[MAXQUIT-1] = '\0';
1894 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1895 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1896 log(DEBUG,"closing fd %d",user->fd);
1898 /* bugfix, cant close() a nonblocking socket (sux!) */
1899 if (user->registered == 7) {
1900 FOREACH_MOD OnUserQuit(user);
1901 WriteCommonExcept(user,"QUIT :%s",reason);
1903 // Q token must go to ALL servers!!!
1904 char buffer[MAXBUF];
1905 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1906 NetSendToAll(buffer);
1909 /* push the socket on a stack of sockets due to be closed at the next opportunity
1910 * 'Client exited' is an exception to this as it means the client side has already
1911 * closed the socket, we don't need to do it.
1913 fd_reap.push_back(user->fd);
1915 bool do_purge = false;
1917 if (user->registered == 7) {
1918 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1922 if (iter != clientlist.end())
1924 log(DEBUG,"deleting user hash value %d",iter->second);
1925 if ((iter->second) && (user->registered == 7)) {
1926 if (iter->second) delete iter->second;
1928 clientlist.erase(iter);
1931 if (user->registered == 7) {
1932 purge_empty_chans();
1937 void kill_link_silent(userrec *user,const char* r)
1939 user_hash::iterator iter = clientlist.find(user->nick);
1941 char reason[MAXBUF];
1943 strncpy(reason,r,MAXBUF);
1945 if (strlen(reason)>MAXQUIT)
1947 reason[MAXQUIT-1] = '\0';
1950 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1951 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1952 log(DEBUG,"closing fd %d",user->fd);
1954 /* bugfix, cant close() a nonblocking socket (sux!) */
1955 if (user->registered == 7) {
1956 FOREACH_MOD OnUserQuit(user);
1957 WriteCommonExcept(user,"QUIT :%s",reason);
1959 // Q token must go to ALL servers!!!
1960 char buffer[MAXBUF];
1961 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1962 NetSendToAll(buffer);
1965 /* push the socket on a stack of sockets due to be closed at the next opportunity
1966 * 'Client exited' is an exception to this as it means the client side has already
1967 * closed the socket, we don't need to do it.
1969 fd_reap.push_back(user->fd);
1971 bool do_purge = false;
1973 if (iter != clientlist.end())
1975 log(DEBUG,"deleting user hash value %d",iter->second);
1976 if ((iter->second) && (user->registered == 7)) {
1977 if (iter->second) delete iter->second;
1979 clientlist.erase(iter);
1982 if (user->registered == 7) {
1983 purge_empty_chans();
1989 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1991 char* Passwd(userrec *user)
1993 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1995 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2003 bool IsDenied(userrec *user)
2005 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2007 if (match(user->host,i->host) && (i->type == CC_DENY))
2018 /* sends out an error notice to all connected clients (not to be used
2021 void send_error(char *s)
2023 log(DEBUG,"send_error: %s",s);
2024 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2026 if (isnick(i->second->nick))
2028 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2032 // fix - unregistered connections receive ERROR, not NOTICE
2033 Write(i->second->fd,"ERROR :%s",s);
2038 void Error(int status)
2040 signal (SIGALRM, SIG_IGN);
2041 signal (SIGPIPE, SIG_IGN);
2042 signal (SIGTERM, SIG_IGN);
2043 signal (SIGABRT, SIG_IGN);
2044 signal (SIGSEGV, SIG_IGN);
2045 signal (SIGURG, SIG_IGN);
2046 signal (SIGKILL, SIG_IGN);
2047 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2048 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2053 int main(int argc, char **argv)
2057 log(DEBUG,"*** InspIRCd starting up!");
2058 if (!FileExists(CONFIG_FILE))
2060 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2061 log(DEBUG,"main: no config");
2062 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2066 for (int i = 1; i < argc; i++)
2068 if (!strcmp(argv[i],"-nofork")) {
2071 if (!strcmp(argv[i],"-wait")) {
2076 strlcpy(MyExecutable,argv[0],MAXBUF);
2078 if (InspIRCd() == ERROR)
2080 log(DEBUG,"main: daemon function bailed");
2081 printf("ERROR: could not initialise. Shutting down.\n");
2088 template<typename T> inline string ConvToStr(const T &in)
2091 if (!(tmp << in)) return string();
2095 /* re-allocates a nick in the user_hash after they change nicknames,
2096 * returns a pointer to the new user as it may have moved */
2098 userrec* ReHashNick(char* Old, char* New)
2100 user_hash::iterator newnick;
2101 user_hash::iterator oldnick = clientlist.find(Old);
2103 log(DEBUG,"ReHashNick: %s %s",Old,New);
2105 if (!strcasecmp(Old,New))
2107 log(DEBUG,"old nick is new nick, skipping");
2108 return oldnick->second;
2111 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2113 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2115 clientlist[New] = new userrec();
2116 clientlist[New] = oldnick->second;
2117 clientlist.erase(oldnick);
2119 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2121 return clientlist[New];
2124 /* adds or updates an entry in the whowas list */
2125 void AddWhoWas(userrec* u)
2127 user_hash::iterator iter = whowas.find(u->nick);
2128 userrec *a = new userrec();
2129 strlcpy(a->nick,u->nick,NICKMAX);
2130 strlcpy(a->ident,u->ident,64);
2131 strlcpy(a->dhost,u->dhost,256);
2132 strlcpy(a->host,u->host,256);
2133 strlcpy(a->fullname,u->fullname,128);
2134 strlcpy(a->server,u->server,256);
2135 a->signon = u->signon;
2137 /* MAX_WHOWAS: max number of /WHOWAS items
2138 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2139 * can be replaced by a newer one
2142 if (iter == whowas.end())
2144 if (whowas.size() == WHOWAS_MAX)
2146 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2148 // 3600 seconds in an hour ;)
2149 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
2151 if (i->second) delete i->second;
2153 log(DEBUG,"added WHOWAS entry, purged an old record");
2160 log(DEBUG,"added fresh WHOWAS entry");
2161 whowas[a->nick] = a;
2166 log(DEBUG,"updated WHOWAS entry");
2167 if (iter->second) delete iter->second;
2173 /* add a client connection to the sockets list */
2174 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2178 char resolved[MAXBUF];
2181 user_hash::iterator iter;
2183 tempnick = ConvToStr(socket) + "-unknown";
2184 sprintf(tn2,"%d-unknown",socket);
2186 iter = clientlist.find(tempnick);
2188 if (iter != clientlist.end()) return;
2191 * It is OK to access the value here this way since we know
2192 * it exists, we just created it above.
2194 * At NO other time should you access a value in a map or a
2195 * hash_map this way.
2197 clientlist[tempnick] = new userrec();
2199 NonBlocking(socket);
2200 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2202 clientlist[tempnick]->fd = socket;
2203 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2204 strncpy(clientlist[tempnick]->host, host,160);
2205 strncpy(clientlist[tempnick]->dhost, host,160);
2206 strncpy(clientlist[tempnick]->server, ServerName,256);
2207 strncpy(clientlist[tempnick]->ident, "unknown",9);
2208 clientlist[tempnick]->registered = 0;
2209 clientlist[tempnick]->signon = TIME+dns_timeout;
2210 clientlist[tempnick]->nping = TIME+240+dns_timeout;
2211 clientlist[tempnick]->lastping = 1;
2212 clientlist[tempnick]->port = port;
2213 strncpy(clientlist[tempnick]->ip,ip,32);
2215 // set the registration timeout for this user
2216 unsigned long class_regtimeout = 90;
2217 int class_flood = 0;
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;
2224 class_flood = i->flood;
2229 clientlist[tempnick]->timeout = TIME+class_regtimeout;
2230 clientlist[tempnick]->flood = class_flood;
2232 for (int i = 0; i < MAXCHANS; i++)
2234 clientlist[tempnick]->chans[i].channel = NULL;
2235 clientlist[tempnick]->chans[i].uc_modes = 0;
2238 if (clientlist.size() == MAXCLIENTS)
2239 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2242 char* e = matches_exception(ip);
2245 char* r = matches_zline(ip);
2248 char reason[MAXBUF];
2249 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2250 kill_link(clientlist[tempnick],reason);
2258 return clientlist.size();
2262 int usercount_invisible(void)
2266 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2268 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2273 int usercount_opers(void)
2277 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2279 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2284 int usercount_unknown(void)
2288 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2290 if ((i->second->fd) && (i->second->registered != 7))
2296 long chancount(void)
2298 return chanlist.size();
2301 long count_servs(void)
2304 //for (int j = 0; j < 255; j++)
2306 // if (servers[j] != NULL)
2312 long servercount(void)
2314 return count_servs()+1;
2320 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2322 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2328 void ShowMOTD(userrec *user)
2330 std::string WholeMOTD = "";
2333 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2336 WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2337 for (int i = 0; i != MOTD.size(); i++)
2339 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2341 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2342 // only one write operation
2343 send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),NULL);
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;
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* e = matches_exception(match_against);
2385 char* r = matches_gline(match_against);
2388 char reason[MAXBUF];
2389 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2390 kill_link_silent(user,reason);
2393 r = matches_kline(user->host);
2396 char reason[MAXBUF];
2397 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2398 kill_link_silent(user,reason);
2403 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2404 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2405 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2406 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2407 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2408 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2409 std::stringstream v;
2410 v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2411 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2412 v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2413 v << std::string(Network);
2414 std::string data005 = v.str();
2415 FOREACH_MOD On005Numeric(data005);
2416 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2417 // so i'd better split it :)
2418 std::stringstream out(data005);
2419 std::string token = "";
2420 std::string line5 = "";
2421 int token_counter = 0;
2425 line5 = line5 + token + " ";
2427 if ((token_counter >= 13) || (out.eof() == true))
2429 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2435 FOREACH_MOD OnUserConnect(user);
2436 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2438 char buffer[MAXBUF];
2439 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);
2440 NetSendToAll(buffer);
2443 /* shows the message of the day, and any other on-logon stuff */
2444 void ConnectUser(userrec *user)
2446 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2447 if ((user->dns_done) && (user->registered >= 3))
2449 FullConnectUser(user);
2453 void handle_version(char **parameters, int pcnt, userrec *user)
2455 char Revision[] = "$Revision$";
2457 char *s1 = Revision;
2459 char *v1 = strtok_r(s1," ",&savept);
2461 char *v2 = strtok_r(s1," ",&savept);
2464 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2468 // calls a handler function for a command
2470 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2472 for (int i = 0; i < cmdlist.size(); i++)
2474 if (!strcasecmp(cmdlist[i].command,commandname))
2476 if (cmdlist[i].handler_function)
2478 if (pcnt>=cmdlist[i].min_params)
2480 if (strchr(user->modes,cmdlist[i].flags_needed))
2482 cmdlist[i].handler_function(parameters,pcnt,user);
2490 void DoSplitEveryone()
2492 bool go_again = true;
2496 for (int i = 0; i < 32; i++)
2500 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2502 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2505 j->CloseConnection();
2506 me[i]->connectors.erase(j);
2514 log(DEBUG,"Removed server. Will remove clients...");
2515 // iterate through the userlist and remove all users on this server.
2516 // because we're dealing with a mesh, we dont have to deal with anything
2517 // "down-route" from this server (nice huh)
2519 char reason[MAXBUF];
2523 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2525 if (strcasecmp(u->second->server,ServerName))
2527 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2528 kill_link(u->second,reason);
2538 char islast(const char* s)
2541 for (int j = 0; j < 32; j++)
2545 for (int k = 0; k < me[j]->connectors.size(); k++)
2547 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2551 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2561 long map_count(const char* s)
2564 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2566 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2572 void force_nickchange(userrec* user,const char* newnick)
2579 FOREACH_RESULT(OnUserPreNick(user,newnick));
2581 kill_link(user,"Nickname collision");
2584 if (matches_qline(newnick))
2586 kill_link(user,"Nickname collision");
2594 strncpy(nick,newnick,MAXBUF);
2596 if (user->registered == 7)
2600 handle_nick(pars,1,user);
2606 int process_parameters(char **command_p,char *parameters)
2611 q = strlen(parameters);
2614 /* no parameters, command_p invalid! */
2617 if (parameters[0] == ':')
2619 command_p[0] = parameters+1;
2624 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2626 /* only one parameter */
2627 command_p[0] = parameters;
2628 if (parameters[0] == ':')
2630 if (strchr(parameters,' ') != NULL)
2638 command_p[j++] = parameters;
2639 for (int i = 0; i <= q; i++)
2641 if (parameters[i] == ' ')
2643 command_p[j++] = parameters+i+1;
2644 parameters[i] = '\0';
2645 if (command_p[j-1][0] == ':')
2647 *command_p[j-1]++; /* remove dodgy ":" */
2649 /* parameter like this marks end of the sequence */
2653 return j; /* returns total number of items in the list */
2656 void process_command(userrec *user, char* cmd)
2660 char *command_p[127];
2661 char p[MAXBUF], temp[MAXBUF];
2662 int i, j, items, cmd_found;
2664 for (int i = 0; i < 127; i++)
2665 command_p[i] = NULL;
2675 if (!strcmp(cmd,""))
2680 int total_params = 0;
2683 for (int q = 0; q < strlen(cmd)-1; q++)
2685 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2688 // found a 'trailing', we dont count them after this.
2696 // another phidjit bug...
2697 if (total_params > 126)
2699 //kill_link(user,"Protocol violation (1)");
2700 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2704 strlcpy(temp,cmd,MAXBUF);
2706 std::string tmp = cmd;
2707 for (int i = 0; i <= MODCOUNT; i++)
2709 std::string oldtmp = tmp;
2710 modules[i]->OnServerRaw(tmp,true,user);
2713 log(DEBUG,"A Module changed the input string!");
2714 log(DEBUG,"New string: %s",tmp.c_str());
2715 log(DEBUG,"Old string: %s",oldtmp.c_str());
2719 strlcpy(cmd,tmp.c_str(),MAXBUF);
2720 strlcpy(temp,cmd,MAXBUF);
2722 if (!strchr(cmd,' '))
2724 /* no parameters, lets skip the formalities and not chop up
2726 log(DEBUG,"About to preprocess command with no params");
2728 command_p[0] = NULL;
2730 for (int i = 0; i <= strlen(cmd); i++)
2732 cmd[i] = toupper(cmd[i]);
2734 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2741 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2742 for (int i = 0; i < strlen(temp); i++)
2744 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2750 /* split the full string into a command plus parameters */
2754 if (strchr(cmd,' '))
2756 for (int i = 0; i <= strlen(cmd); i++)
2758 /* capitalise the command ONLY, leave params intact */
2759 cmd[i] = toupper(cmd[i]);
2760 /* are we nearly there yet?! :P */
2764 parameters = cmd+i+1;
2772 for (int i = 0; i <= strlen(cmd); i++)
2774 cmd[i] = toupper(cmd[i]);
2781 if (strlen(command)>MAXCOMMAND)
2783 //kill_link(user,"Protocol violation (2)");
2784 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2788 for (int x = 0; x < strlen(command); x++)
2790 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2792 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2794 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2796 //kill_link(user,"Protocol violation (3)");
2797 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2804 for (int i = 0; i != cmdlist.size(); i++)
2806 if (strcmp(cmdlist[i].command,""))
2808 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2810 log(DEBUG,"Found matching command");
2814 if (strcmp(parameters,""))
2816 items = process_parameters(command_p,parameters);
2821 command_p[0] = NULL;
2827 command_p[0] = NULL;
2832 log(DEBUG,"Processing command");
2834 /* activity resets the ping pending timer */
2835 user->nping = TIME + 120;
2836 if ((items) < cmdlist[i].min_params)
2838 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2839 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2842 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2844 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2845 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2849 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2851 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2852 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2856 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2858 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2860 if ((!isnick(user->nick)) || (user->registered != 7))
2862 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2863 WriteServ(user->fd,"451 %s :You have not registered",command);
2867 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2869 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2870 if (cmdlist[i].handler_function)
2872 /* ikky /stats counters */
2877 user->bytes_in += strlen(temp);
2879 user->bytes_out+=strlen(temp);
2882 cmdlist[i].use_count++;
2883 cmdlist[i].total_bytes+=strlen(temp);
2886 /* WARNING: nothing may come after the
2887 * command handler call, as the handler
2888 * may free the user structure! */
2890 cmdlist[i].handler_function(command_p,items,user);
2896 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2897 WriteServ(user->fd,"451 %s :You have not registered",command);
2905 if ((!cmd_found) && (user))
2907 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2908 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2913 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2916 /* create the command and push it onto the table */
2917 strlcpy(comm.command,cmd,MAXBUF);
2918 comm.handler_function = f;
2919 comm.flags_needed = flags;
2920 comm.min_params = minparams;
2922 comm.total_bytes = 0;
2923 cmdlist.push_back(comm);
2924 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2927 void SetupCommandTable(void)
2929 createcommand("USER",handle_user,0,4);
2930 createcommand("NICK",handle_nick,0,1);
2931 createcommand("QUIT",handle_quit,0,0);
2932 createcommand("VERSION",handle_version,0,0);
2933 createcommand("PING",handle_ping,0,1);
2934 createcommand("PONG",handle_pong,0,1);
2935 createcommand("ADMIN",handle_admin,0,0);
2936 createcommand("PRIVMSG",handle_privmsg,0,2);
2937 createcommand("INFO",handle_info,0,0);
2938 createcommand("TIME",handle_time,0,0);
2939 createcommand("WHOIS",handle_whois,0,1);
2940 createcommand("WALLOPS",handle_wallops,'o',1);
2941 createcommand("NOTICE",handle_notice,0,2);
2942 createcommand("JOIN",handle_join,0,1);
2943 createcommand("NAMES",handle_names,0,1);
2944 createcommand("PART",handle_part,0,1);
2945 createcommand("KICK",handle_kick,0,2);
2946 createcommand("MODE",handle_mode,0,1);
2947 createcommand("TOPIC",handle_topic,0,1);
2948 createcommand("WHO",handle_who,0,1);
2949 createcommand("MOTD",handle_motd,0,0);
2950 createcommand("RULES",handle_rules,0,0);
2951 createcommand("OPER",handle_oper,0,2);
2952 createcommand("LIST",handle_list,0,0);
2953 createcommand("DIE",handle_die,'o',1);
2954 createcommand("RESTART",handle_restart,'o',1);
2955 createcommand("KILL",handle_kill,'o',2);
2956 createcommand("REHASH",handle_rehash,'o',0);
2957 createcommand("LUSERS",handle_lusers,0,0);
2958 createcommand("STATS",handle_stats,0,1);
2959 createcommand("USERHOST",handle_userhost,0,1);
2960 createcommand("AWAY",handle_away,0,0);
2961 createcommand("ISON",handle_ison,0,0);
2962 createcommand("SUMMON",handle_summon,0,0);
2963 createcommand("USERS",handle_users,0,0);
2964 createcommand("INVITE",handle_invite,0,2);
2965 createcommand("PASS",handle_pass,0,1);
2966 createcommand("TRACE",handle_trace,'o',0);
2967 createcommand("WHOWAS",handle_whowas,0,1);
2968 createcommand("CONNECT",handle_connect,'o',1);
2969 createcommand("SQUIT",handle_squit,'o',0);
2970 createcommand("MODULES",handle_modules,'o',0);
2971 createcommand("LINKS",handle_links,0,0);
2972 createcommand("MAP",handle_map,0,0);
2973 createcommand("KLINE",handle_kline,'o',1);
2974 createcommand("GLINE",handle_gline,'o',1);
2975 createcommand("ZLINE",handle_zline,'o',1);
2976 createcommand("QLINE",handle_qline,'o',1);
2977 createcommand("ELINE",handle_eline,'o',1);
2978 createcommand("SERVER",handle_server,0,0);
2981 void process_buffer(const char* cmdbuf,userrec *user)
2985 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2992 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2995 if (!strcmp(cmdbuf,""))
2999 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3001 strlcpy(cmd,cmdbuf,MAXBUF);
3002 if (!strcmp(cmd,""))
3006 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3008 cmd[strlen(cmd)-1] = '\0';
3010 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3012 cmd[strlen(cmd)-1] = '\0';
3015 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3017 cmd[strlen(cmd)-1] = '\0';
3020 if (!strcmp(cmd,""))
3024 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3026 if ((user) && (cmd))
3028 process_command(user,cmd);
3032 void DoSync(serverrec* serv, char* tcp_host)
3035 log(DEBUG,"Sending sync");
3036 // send start of sync marker: Y <timestamp>
3037 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3038 // except the ones its receiving it from.
3039 snprintf(data,MAXBUF,"Y %d",TIME);
3040 serv->SendPacket(data,tcp_host);
3041 // send users and channels
3042 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3044 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);
3045 serv->SendPacket(data,tcp_host);
3046 if (strchr(u->second->modes,'o'))
3048 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3049 serv->SendPacket(data,tcp_host);
3051 for (int i = 0; i <= MODCOUNT; i++)
3053 string_list l = modules[i]->OnUserSync(u->second);
3054 for (int j = 0; j < l.size(); j++)
3056 strlcpy(data,l[j].c_str(),MAXBUF);
3057 serv->SendPacket(data,tcp_host);
3060 if (strcmp(chlist(u->second),""))
3062 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3063 serv->SendPacket(data,tcp_host);
3066 // send channel modes, topics etc...
3067 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3069 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3070 serv->SendPacket(data,tcp_host);
3071 for (int i = 0; i <= MODCOUNT; i++)
3073 string_list l = modules[i]->OnChannelSync(c->second);
3074 for (int j = 0; j < l.size(); j++)
3076 strlcpy(data,l[j].c_str(),MAXBUF);
3077 serv->SendPacket(data,tcp_host);
3080 if (strcmp(c->second->topic,""))
3082 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3083 serv->SendPacket(data,tcp_host);
3085 // send current banlist
3087 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3089 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3090 serv->SendPacket(data,tcp_host);
3093 // sync global zlines, glines, etc
3094 sync_xlines(serv,tcp_host);
3096 for (int j = 0; j < 32; j++)
3100 for (int k = 0; k < me[j]->connectors.size(); k++)
3102 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3104 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3105 serv->SendPacket(data,tcp_host);
3106 NetSendMyRoutingTable();
3112 snprintf(data,MAXBUF,"F %d",TIME);
3113 serv->SendPacket(data,tcp_host);
3114 log(DEBUG,"Sent sync");
3115 // ircd sends its serverlist after the end of sync here
3119 void NetSendMyRoutingTable()
3121 // send out a line saying what is reachable to us.
3122 // E.g. if A is linked to B C and D, send out:
3124 // if its only linked to B and D send out:
3126 // if it has no links, dont even send out the line at all.
3127 char buffer[MAXBUF];
3128 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3129 bool sendit = false;
3130 for (int i = 0; i < 32; i++)
3134 for (int j = 0; j < me[i]->connectors.size(); j++)
3136 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3138 strlcat(buffer," ",MAXBUF);
3139 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3146 NetSendToAll(buffer);
3150 void DoSplit(const char* params)
3152 bool go_again = true;
3156 for (int i = 0; i < 32; i++)
3160 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3162 if (!strcasecmp(j->GetServerName().c_str(),params))
3165 j->CloseConnection();
3166 me[i]->connectors.erase(j);
3174 log(DEBUG,"Removed server. Will remove clients...");
3175 // iterate through the userlist and remove all users on this server.
3176 // because we're dealing with a mesh, we dont have to deal with anything
3177 // "down-route" from this server (nice huh)
3179 char reason[MAXBUF];
3180 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3184 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3186 if (!strcasecmp(u->second->server,params))
3188 kill_link(u->second,reason);
3196 // removes a server. Will NOT remove its users!
3198 void RemoveServer(const char* name)
3200 bool go_again = true;
3204 for (int i = 0; i < 32; i++)
3208 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3210 if (!strcasecmp(j->GetServerName().c_str(),name))
3213 j->CloseConnection();
3214 me[i]->connectors.erase(j);
3225 int reap_counter = 0;
3229 struct sockaddr_in client,server;
3230 char addrs[MAXBUF][255];
3231 int incomingSockfd, result = TRUE;
3234 int selectResult = 0, selectResult2 = 0;
3235 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3236 char resolvedHost[MAXBUF];
3240 log_file = fopen("ircd.log","a+");
3243 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3247 log(DEBUG,"InspIRCd: startup: begin");
3251 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3253 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3255 SetupCommandTable();
3256 log(DEBUG,"InspIRCd: startup: default command table set up");
3258 ReadConfig(true,NULL);
3259 if (strcmp(DieValue,""))
3261 printf("WARNING: %s\n\n",DieValue);
3262 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3265 log(DEBUG,"InspIRCd: startup: read config");
3267 int count2 = 0, count3 = 0;
3269 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3271 ConfValue("bind","port",count,configToken,&config_f);
3272 ConfValue("bind","address",count,Addr,&config_f);
3273 ConfValue("bind","type",count,Type,&config_f);
3274 if (!strcmp(Type,"servers"))
3276 char Default[MAXBUF];
3277 strcpy(Default,"no");
3278 ConfValue("bind","default",count,Default,&config_f);
3279 if (strchr(Default,'y'))
3281 defaultRoute = count3;
3282 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3284 me[count3] = new serverrec(ServerName,100L,false);
3285 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3287 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3296 ports[count2] = atoi(configToken);
3297 strlcpy(addrs[count2],Addr,256);
3300 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3303 UDPportCount = count3;
3305 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3307 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3311 /* BugFix By Craig! :p */
3313 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3315 char modfile[MAXBUF];
3316 ConfValue("module","name",count2,configToken,&config_f);
3317 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3318 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3319 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3320 /* If The File Doesnt exist, Trying to load it
3321 * Will Segfault the IRCd.. So, check to see if
3322 * it Exists, Before Proceeding. */
3323 if (FileExists(modfile))
3325 factory[count] = new ircd_module(modfile);
3326 if (factory[count]->LastError())
3328 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3329 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3332 if (factory[count]->factory)
3334 modules[count] = factory[count]->factory->CreateModule();
3335 /* save the module and the module's classfactory, if
3336 * this isnt done, random crashes can occur :/ */
3337 module_names.push_back(modfile);
3341 log(DEBUG,"Unable to load %s",modfile);
3342 printf("Unable to load %s\nExiting...\n",modfile);
3345 /* Increase the Count */
3350 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3351 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3354 MODCOUNT = count - 1;
3355 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3357 printf("\nInspIRCd is now running!\n");
3359 startup_time = time(NULL);
3363 log(VERBOSE,"Not forking as -nofork was specified");
3367 if (DaemonSeed() == ERROR)
3369 log(DEBUG,"InspIRCd: startup: can't daemonise");
3370 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3376 ConfValue("pid","file",0,PID,&config_f);
3380 /* setup select call */
3381 FD_ZERO(&selectFds);
3382 log(DEBUG,"InspIRCd: startup: zero selects");
3383 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3385 for (count = 0; count < portCount; count++)
3387 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3389 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3392 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3394 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3396 else /* well we at least bound to one socket so we'll continue */
3402 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3404 /* if we didn't bind to anything then abort */
3405 if (boundPortCount == 0)
3407 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3412 length = sizeof (client);
3413 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3417 tvs.tv_usec = 7000L;
3424 tval.tv_usec = 7000L;
3426 int total_in_this_set = 0;
3428 bool expire_run = false;
3430 /* main loop, this never returns */
3433 #ifdef _POSIX_PRIORITY_SCHEDULING
3440 // we only read time() once per iteration rather than tons of times!
3443 user_hash::iterator count2 = clientlist.begin();
3445 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3446 // them in a list, then reap the list every second or so.
3447 if (((TIME % 5) == 0) && (!expire_run))
3452 if ((TIME % 5) == 1)
3454 if (reap_counter>300)
3456 if (fd_reap.size() > 0)
3458 for( int n = 0; n < fd_reap.size(); n++)
3460 //Blocking(fd_reap[n]);
3462 shutdown (fd_reap[n],2);
3463 //NonBlocking(fd_reap[n]);
3471 FD_ZERO(&serverfds);
3473 for (int x = 0; x != UDPportCount; x++)
3476 FD_SET(me[x]->fd, &serverfds);
3479 // serverFds timevals went here
3481 tvs.tv_usec = 7000L;
3482 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3485 for (int x = 0; x != UDPportCount; x++)
3487 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3489 char remotehost[MAXBUF],resolved[MAXBUF];
3490 length = sizeof (client);
3491 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3492 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3493 if(CleanAndResolve(resolved, remotehost) != TRUE)
3495 strlcpy(resolved,remotehost,MAXBUF);
3497 // add to this connections ircd_connector vector
3498 // *FIX* - we need the LOCAL port not the remote port in &client!
3499 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3504 for (int x = 0; x < UDPportCount; x++)
3506 std::deque<std::string> msgs;
3508 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3510 for (int ctr = 0; ctr < msgs.size(); ctr++)
3512 char udp_msg[MAXBUF];
3513 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3514 if (strlen(udp_msg)<1)
3516 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3519 // during a netburst, send all data to all other linked servers
3520 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3522 if (is_uline(tcp_host))
3524 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3526 NetSendToAllExcept(tcp_host,udp_msg);
3530 NetSendToAllExcept(tcp_host,udp_msg);
3532 FOREACH_MOD OnPacketReceive(udp_msg);
3533 handle_link_packet(udp_msg, tcp_host, me[x]);
3540 while (count2 != clientlist.end())
3543 total_in_this_set = 0;
3545 user_hash::iterator xcount = count2;
3546 user_hash::iterator endingiter = count2;
3548 if (count2 == clientlist.end()) break;
3551 if (count2->second->fd != 0)
3553 // assemble up to 64 sockets into an fd_set
3554 // to implement a pooling mechanism.
3556 // This should be up to 64x faster than the
3557 // old implementation.
3558 while (total_in_this_set < 64)
3560 if (count2 != clientlist.end())
3562 // we don't check the state of remote users.
3563 if (count2->second->fd > 0)
3565 FD_SET (count2->second->fd, &sfd);
3567 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3568 // their connection class.
3569 if ((TIME > count2->second->timeout) && (count2->second->registered != 7))
3571 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3572 kill_link(count2->second,"Registration timeout");
3575 if ((TIME > count2->second->signon) && (count2->second->registered == 3))
3577 count2->second->dns_done = true;
3578 FullConnectUser(count2->second);
3581 if ((count2->second->dns_done) && (count2->second->registered == 3)) // both NICK and USER... and DNS
3583 FullConnectUser(count2->second);
3586 if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3588 if ((!count2->second->lastping) && (count2->second->registered == 7))
3590 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3591 kill_link(count2->second,"Ping timeout");
3594 Write(count2->second->fd,"PING :%s",ServerName);
3595 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3596 count2->second->lastping = 0;
3597 count2->second->nping = TIME+120;
3601 total_in_this_set++;
3606 endingiter = count2;
3607 count2 = xcount; // roll back to where we were
3611 // tvals defined here
3613 tval.tv_usec = 7000L;
3614 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3616 // now loop through all of the items in this pool if any are waiting
3617 //if (selectResult2 > 0)
3618 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3621 #ifdef _POSIX_PRIORITY_SCHEDULING
3626 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3628 memset(data, 0, 10240);
3629 result = read(count2a->second->fd, data, 10240);
3633 userrec* current = count2a->second;
3634 int currfd = current->fd;
3635 char* l = strtok(data,"\n");
3640 if ((floodlines > current->flood) && (current->flood != 0))
3642 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3643 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3644 kill_link(current,"Excess flood");
3647 char sanitized[NetBufferSize];
3648 memset(sanitized, 0, NetBufferSize);
3650 for (int pt = 0; pt < strlen(l); pt++)
3654 sanitized[ptt++] = l[pt];
3657 sanitized[ptt] = '\0';
3658 if (strlen(sanitized))
3662 // we're gonna re-scan to check if the nick is gone, after every
3663 // command - if it has, we're gonna bail
3664 bool find_again = false;
3665 process_buffer(sanitized,current);
3667 // look for the user's record in case it's changed
3668 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3670 if (c2->second->fd == currfd)
3672 // found again, update pointer
3673 current == c2->second;
3682 l = strtok(NULL,"\n");
3687 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3689 log(DEBUG,"killing: %s",count2a->second->nick);
3690 kill_link(count2a->second,strerror(errno));
3694 // result EAGAIN means nothing read
3695 if (result == EAGAIN)
3703 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3704 kill_link(count2a->second,"Client exited");
3705 // must bail here? kill_link removes the hash, corrupting the iterator
3706 log(DEBUG,"Bailing from client exit");
3710 else if (result > 0)
3715 for (int q = 0; q < total_in_this_set; q++)
3717 // there is no iterator += operator :(
3718 //if (count2 != clientlist.end())
3725 // set up select call
3726 for (count = 0; count < boundPortCount; count++)
3728 FD_SET (openSockfd[count], &selectFds);
3732 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3734 /* select is reporting a waiting socket. Poll them all to find out which */
3735 if (selectResult > 0)
3737 char target[MAXBUF], resolved[MAXBUF];
3738 for (count = 0; count < boundPortCount; count++)
3740 if (FD_ISSET (openSockfd[count], &selectFds))
3742 length = sizeof (client);
3743 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3745 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3746 strlcpy (resolved, target, MAXBUF);
3748 if (incomingSockfd < 0)
3750 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3751 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3755 AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3756 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3763 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3766 close (incomingSockfd);