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"
60 #define nspace __gnu_cxx
65 int LogLevel = DEFAULT;
66 char ServerName[MAXBUF];
68 char ServerDesc[MAXBUF];
69 char AdminName[MAXBUF];
70 char AdminEmail[MAXBUF];
71 char AdminNick[MAXBUF];
73 char restartpass[MAXBUF];
77 char PrefixQuit[MAXBUF];
78 char DieValue[MAXBUF];
80 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
81 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
83 time_t startup_time = time(NULL);
84 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
85 extern int MaxWhoResults;
88 extern vector<Module*> modules;
89 std::vector<std::string> module_names;
90 extern vector<ircd_module*> factory;
91 std::vector<int> fd_reap;
99 template<> struct nspace::hash<in_addr>
101 size_t operator()(const struct in_addr &a) const
104 memcpy(&q,&a,sizeof(size_t));
109 template<> struct nspace::hash<string>
111 size_t operator()(const string &s) const
114 static struct hash<const char *> strhash;
126 bool operator()(const string& s1, const string& s2) const
128 char a[MAXBUF],b[MAXBUF];
129 strcpy(a,s1.c_str());
130 strcpy(b,s2.c_str());
131 return (strcasecmp(a,b) == 0);
136 struct InAddr_HashComp
139 bool operator()(const in_addr &s1, const in_addr &s2) const
144 memcpy(&q,&s1,sizeof(size_t));
145 memcpy(&p,&s2,sizeof(size_t));
153 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
154 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
155 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
156 typedef std::deque<command_t> command_table;
162 user_hash clientlist;
165 command_table cmdlist;
172 struct linger linger = { 0 };
173 char bannerBuffer[MAXBUF];
174 int boundPortCount = 0;
175 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
176 int defaultRoute = 0;
180 long MyKey = C.GenKey();
184 int has_channel(userrec *u, chanrec *c);
185 int usercount(chanrec *c);
186 int usercount_i(chanrec *c);
187 void update_stats_l(int fd,int data_out);
188 char* Passwd(userrec *user);
189 bool IsDenied(userrec *user);
190 void AddWhoWas(userrec* u);
192 std::vector<long> auth_cookies;
193 std::stringstream config_f(stringstream::in | stringstream::out);
199 char Revision[] = "$Revision$";
202 char *v1 = strtok_r(s1," ",&savept);
204 char *v2 = strtok_r(s1," ",&savept);
206 return (long)(atof(v2)*10000);
210 std::string getservername()
215 std::string getserverdesc()
220 std::string getnetworkname()
225 std::string getadminname()
230 std::string getadminemail()
235 std::string getadminnick()
240 void log(int level,char *text, ...)
242 char textbuffer[MAXBUF];
245 struct tm * timeinfo;
246 if (level < LogLevel)
250 timeinfo = localtime (&rawtime);
255 va_start (argsPtr, text);
256 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
258 strcpy(b,asctime(timeinfo));
259 b[strlen(b)-1] = ':';
260 fprintf(log_file,"%s %s\n",b,textbuffer);
263 // nofork enabled? display it on terminal too
264 printf("%s %s\n",b,textbuffer);
269 void readfile(file_cache &F, const char* fname)
272 char linebuf[MAXBUF];
274 log(DEBUG,"readfile: loading %s",fname);
276 file = fopen(fname,"r");
281 fgets(linebuf,sizeof(linebuf),file);
282 linebuf[strlen(linebuf)-1]='\0';
283 if (!strcmp(linebuf,""))
289 F.push_back(linebuf);
296 log(DEBUG,"readfile: failed to load file: %s",fname);
298 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
301 void ReadConfig(void)
303 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
306 LoadConf(CONFIG_FILE,&config_f);
308 ConfValue("server","name",0,ServerName,&config_f);
309 ConfValue("server","description",0,ServerDesc,&config_f);
310 ConfValue("server","network",0,Network,&config_f);
311 ConfValue("admin","name",0,AdminName,&config_f);
312 ConfValue("admin","email",0,AdminEmail,&config_f);
313 ConfValue("admin","nick",0,AdminNick,&config_f);
314 ConfValue("files","motd",0,motd,&config_f);
315 ConfValue("files","rules",0,rules,&config_f);
316 ConfValue("power","diepass",0,diepass,&config_f);
317 ConfValue("power","pause",0,pauseval,&config_f);
318 ConfValue("power","restartpass",0,restartpass,&config_f);
319 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
320 ConfValue("die","value",0,DieValue,&config_f);
321 ConfValue("options","loglevel",0,dbg,&config_f);
322 ConfValue("options","netbuffersize",0,NB,&config_f);
323 ConfValue("options","maxwho",0,MW,&config_f);
324 NetBufferSize = atoi(NB);
325 MaxWhoResults = atoi(MW);
326 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
328 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
329 NetBufferSize = 10240;
331 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
333 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
336 if (!strcmp(dbg,"debug"))
338 if (!strcmp(dbg,"verbose"))
340 if (!strcmp(dbg,"default"))
342 if (!strcmp(dbg,"sparse"))
344 if (!strcmp(dbg,"none"))
347 log(DEFAULT,"Reading message of the day...");
348 readfile(RULES,rules);
349 log(DEFAULT,"Reading connect classes...");
351 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
354 ConfValue("connect","allow",i,Value,&config_f);
355 ConfValue("connect","timeout",i,timeout,&config_f);
356 ConfValue("connect","flood",i,flood,&config_f);
357 if (strcmp(Value,""))
359 strcpy(c.host,Value);
362 ConfValue("connect","password",i,Value,&config_f);
363 strcpy(c.pass,Value);
364 c.registration_timeout = 90; // default is 2 minutes
365 c.flood = atoi(flood);
368 c.registration_timeout = atoi(timeout);
370 Classes.push_back(c);
371 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
375 ConfValue("connect","deny",i,Value,&config_f);
376 strcpy(c.host,Value);
378 Classes.push_back(c);
379 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
383 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
384 read_xline_defaults();
385 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
387 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
390 /* write formatted text to a socket, in same format as printf */
392 void Write(int sock,char *text, ...)
396 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
399 char textbuffer[MAXBUF];
403 va_start (argsPtr, text);
404 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
406 sprintf(tb,"%s\r\n",textbuffer);
410 write(sock,tb,strlen(tb));
411 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
415 /* write a server formatted numeric response to a single socket */
417 void WriteServ(int sock, char* text, ...)
421 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
424 char textbuffer[MAXBUF],tb[MAXBUF];
426 va_start (argsPtr, text);
428 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
430 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
434 write(sock,tb,strlen(tb));
435 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
439 /* write text from an originating user to originating user */
441 void WriteFrom(int sock, userrec *user,char* text, ...)
443 if ((!text) || (!user))
445 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
448 char textbuffer[MAXBUF],tb[MAXBUF];
450 va_start (argsPtr, text);
452 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
454 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
458 write(sock,tb,strlen(tb));
459 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
463 /* write text to an destination user from a source user (e.g. user privmsg) */
465 void WriteTo(userrec *source, userrec *dest,char *data, ...)
467 if ((!dest) || (!data))
469 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
472 char textbuffer[MAXBUF],tb[MAXBUF];
474 va_start (argsPtr, data);
475 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
479 // if no source given send it from the server.
482 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
486 WriteFrom(dest->fd,source,"%s",textbuffer);
490 /* write formatted text from a source user to all users on a channel
491 * including the sender (NOT for privmsg, notice etc!) */
493 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
495 if ((!Ptr) || (!user) || (!text))
497 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
500 char textbuffer[MAXBUF];
502 va_start (argsPtr, text);
503 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
505 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
507 if (has_channel(i->second,Ptr))
509 WriteTo(user,i->second,"%s",textbuffer);
514 /* write formatted text from a source user to all users on a channel
515 * including the sender (NOT for privmsg, notice etc!) doesnt send to
516 * users on remote servers */
518 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
520 if ((!Ptr) || (!text))
522 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
525 char textbuffer[MAXBUF];
527 va_start (argsPtr, text);
528 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
530 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
532 if (has_channel(i->second,Ptr))
534 if (i->second->fd != -1)
538 WriteServ(i->second->fd,"%s",textbuffer);
542 WriteTo(user,i->second,"%s",textbuffer);
550 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
552 if ((!Ptr) || (!user) || (!text))
554 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
557 char textbuffer[MAXBUF];
559 va_start (argsPtr, text);
560 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
562 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
566 if (has_channel(i->second,Ptr))
568 WriteServ(i->second->fd,"%s",textbuffer);
575 /* write formatted text from a source user to all users on a channel except
576 * for the sender (for privmsg etc) */
578 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
580 if ((!Ptr) || (!user) || (!text))
582 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
585 char textbuffer[MAXBUF];
587 va_start (argsPtr, text);
588 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
591 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
595 if (has_channel(i->second,Ptr) && (user != i->second))
597 WriteTo(user,i->second,"%s",textbuffer);
604 std::string GetServerDescription(char* servername)
606 for (int j = 0; j < 32; j++)
610 for (int k = 0; k < me[j]->connectors.size(); k++)
612 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
614 return me[j]->connectors[k].GetDescription();
618 return ServerDesc; // not a remote server that can be found, it must be me.
623 /* write a formatted string to all users who share at least one common
624 * channel, including the source user e.g. for use in NICK */
626 void WriteCommon(userrec *u, char* text, ...)
630 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
634 if (u->registered != 7) {
635 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
639 char textbuffer[MAXBUF];
641 va_start (argsPtr, text);
642 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
645 WriteFrom(u->fd,u,"%s",textbuffer);
647 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
651 if (common_channels(u,i->second) && (i->second != u))
653 WriteFrom(i->second->fd,u,"%s",textbuffer);
659 /* write a formatted string to all users who share at least one common
660 * channel, NOT including the source user e.g. for use in QUIT */
662 void WriteCommonExcept(userrec *u, char* text, ...)
666 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
670 if (u->registered != 7) {
671 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
675 char textbuffer[MAXBUF];
677 va_start (argsPtr, text);
678 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
681 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
685 if ((common_channels(u,i->second)) && (u != i->second))
687 WriteFrom(i->second->fd,u,"%s",textbuffer);
693 void WriteOpers(char* text, ...)
697 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
701 char textbuffer[MAXBUF];
703 va_start (argsPtr, text);
704 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
707 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
711 if (strchr(i->second->modes,'o'))
713 if (strchr(i->second->modes,'s'))
715 // send server notices to all with +s
716 // (TODO: needs SNOMASKs)
717 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
724 // returns TRUE of any users on channel C occupy server 'servername'.
726 bool ChanAnyOnThisServer(chanrec *c,char* servername)
728 log(DEBUG,"ChanAnyOnThisServer");
729 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
731 if (has_channel(i->second,c))
733 if (!strcasecmp(i->second->server,servername))
742 // returns true if user 'u' shares any common channels with any users on server 'servername'
744 bool CommonOnThisServer(userrec* u,const char* servername)
746 log(DEBUG,"ChanAnyOnThisServer");
747 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
749 if ((common_channels(u,i->second)) && (u != i->second))
751 if (!strcasecmp(i->second->server,servername))
753 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
762 void NetSendToCommon(userrec* u, char* s)
765 snprintf(buffer,MAXBUF,"%s",s);
767 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
769 for (int j = 0; j < 32; j++)
773 for (int k = 0; k < me[j]->connectors.size(); k++)
775 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
777 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
785 void NetSendToAll(char* s)
788 snprintf(buffer,MAXBUF,"%s",s);
790 log(DEBUG,"NetSendToAll: '%s'",s);
792 for (int j = 0; j < 32; j++)
796 for (int k = 0; k < me[j]->connectors.size(); k++)
798 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
804 void NetSendToAllAlive(char* s)
807 snprintf(buffer,MAXBUF,"%s",s);
809 log(DEBUG,"NetSendToAllAlive: '%s'",s);
811 for (int j = 0; j < 32; j++)
815 for (int k = 0; k < me[j]->connectors.size(); k++)
817 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
819 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
823 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
831 void NetSendToOne(char* target,char* s)
834 snprintf(buffer,MAXBUF,"%s",s);
836 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
838 for (int j = 0; j < 32; j++)
842 for (int k = 0; k < me[j]->connectors.size(); k++)
844 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
846 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
853 void NetSendToAllExcept(const char* target,char* s)
856 snprintf(buffer,MAXBUF,"%s",s);
858 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
860 for (int j = 0; j < 32; j++)
864 for (int k = 0; k < me[j]->connectors.size(); k++)
866 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
868 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
876 void WriteMode(const char* modes, int flags, const char* text, ...)
878 if ((!text) || (!modes) || (!flags))
880 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
884 char textbuffer[MAXBUF];
886 va_start (argsPtr, text);
887 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
890 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
894 bool send_to_user = false;
899 for (int n = 0; n < strlen(modes); n++)
901 if (!hasumode(i->second,modes[n]))
903 send_to_user = false;
908 else if (flags == WM_OR)
910 send_to_user = false;
911 for (int n = 0; n < strlen(modes); n++)
913 if (hasumode(i->second,modes[n]))
923 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
930 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
932 if ((!text) || (!source))
934 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
939 char textbuffer[MAXBUF];
941 va_start (argsPtr, text);
942 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
945 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
949 if (strchr(i->second->modes,'w'))
951 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
959 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
960 NetSendToAll(buffer);
964 /* convert a string to lowercase. Note following special circumstances
965 * taken from RFC 1459. Many "official" server branches still hold to this
966 * rule so i will too;
968 * Because of IRC's scandanavian origin, the characters {}| are
969 * considered to be the lower case equivalents of the characters []\,
970 * respectively. This is a critical issue when determining the
971 * equivalence of two nicknames.
974 void strlower(char *n)
980 for (int i = 0; i != strlen(n); i++)
982 n[i] = tolower(n[i]);
994 /* Find a user record by nickname and return a pointer to it */
996 userrec* Find(string nick)
998 user_hash::iterator iter = clientlist.find(nick);
1000 if (iter == clientlist.end())
1001 /* Couldn't find it */
1004 return iter->second;
1007 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1009 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1013 if (i->second->fd == fd)
1015 i->second->bytes_out+=data_out;
1016 i->second->cmds_out++;
1023 /* find a channel record by channel name and return a pointer to it */
1025 chanrec* FindChan(const char* chan)
1029 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1033 chan_hash::iterator iter = chanlist.find(chan);
1035 if (iter == chanlist.end())
1036 /* Couldn't find it */
1039 return iter->second;
1043 void purge_empty_chans(void)
1045 int go_again = 1, purge = 0;
1050 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1053 if (!usercount(i->second))
1055 /* kill the record */
1056 if (i != chanlist.end())
1058 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1068 log(DEBUG,"skipped purge for %s",i->second->name);
1073 log(DEBUG,"completed channel purge, killed %d",purge);
1077 char scratch[MAXBUF];
1078 char sparam[MAXBUF];
1080 char* chanmodes(chanrec *chan)
1084 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1091 if (chan->noexternal)
1093 strncat(scratch,"n",MAXMODES);
1095 if (chan->topiclock)
1097 strncat(scratch,"t",MAXMODES);
1099 if (strcmp(chan->key,""))
1101 strncat(scratch,"k",MAXMODES);
1105 strncat(scratch,"l",MAXMODES);
1107 if (chan->inviteonly)
1109 strncat(scratch,"i",MAXMODES);
1111 if (chan->moderated)
1113 strncat(scratch,"m",MAXMODES);
1117 strncat(scratch,"s",MAXMODES);
1119 if (chan->c_private)
1121 strncat(scratch,"p",MAXMODES);
1123 if (strcmp(chan->key,""))
1125 strncat(sparam," ",MAXBUF);
1126 strncat(sparam,chan->key,MAXBUF);
1131 sprintf(foo," %d",chan->limit);
1132 strncat(sparam,foo,MAXBUF);
1134 if (strlen(chan->custom_modes))
1136 strncat(scratch,chan->custom_modes,MAXMODES);
1137 for (int z = 0; z < strlen(chan->custom_modes); z++)
1139 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1142 strncat(sparam," ",MAXBUF);
1143 strncat(sparam,extparam.c_str(),MAXBUF);
1147 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1148 strncat(scratch,sparam,MAXMODES);
1153 /* compile a userlist of a channel into a string, each nick seperated by
1154 * spaces and op, voice etc status shown as @ and + */
1156 void userlist(userrec *user,chanrec *c)
1158 if ((!c) || (!user))
1160 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1164 sprintf(list,"353 %s = %s :", user->nick, c->name);
1165 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1167 if (has_channel(i->second,c))
1169 if (isnick(i->second->nick))
1171 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1173 /* user is +i, and source not on the channel, does not show
1174 * nick in NAMES list */
1177 strcat(list,cmode(i->second,c));
1178 strcat(list,i->second->nick);
1180 if (strlen(list)>(480-NICKMAX))
1182 /* list overflowed into
1183 * multiple numerics */
1184 WriteServ(user->fd,list);
1185 sprintf(list,"353 %s = %s :", user->nick, c->name);
1190 /* if whats left in the list isnt empty, send it */
1191 if (list[strlen(list)-1] != ':')
1193 WriteServ(user->fd,list);
1197 /* return a count of the users on a specific channel accounting for
1198 * invisible users who won't increase the count. e.g. for /LIST */
1200 int usercount_i(chanrec *c)
1207 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1212 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1216 if (has_channel(i->second,c))
1218 if (isnick(i->second->nick))
1220 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1222 /* user is +i, and source not on the channel, does not show
1223 * nick in NAMES list */
1231 log(DEBUG,"usercount_i: %s %d",c->name,count);
1236 int usercount(chanrec *c)
1243 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1248 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1252 if (has_channel(i->second,c))
1254 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1261 log(DEBUG,"usercount: %s %d",c->name,count);
1266 /* add a channel to a user, creating the record for it if needed and linking
1267 * it to the user record */
1269 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1271 if ((!user) || (!cn))
1273 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1282 strncpy(cname,cn,MAXBUF);
1284 // we MUST declare this wherever we use FOREACH_RESULT
1287 if (strlen(cname) > CHANMAX-1)
1289 cname[CHANMAX-1] = '\0';
1292 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1294 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1296 return NULL; // already on the channel!
1300 if (!FindChan(cname))
1302 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1307 /* create a new one */
1308 log(DEBUG,"add_channel: creating: %s",cname);
1310 chanlist[cname] = new chanrec();
1312 strcpy(chanlist[cname]->name, cname);
1313 chanlist[cname]->topiclock = 1;
1314 chanlist[cname]->noexternal = 1;
1315 chanlist[cname]->created = time(NULL);
1316 strcpy(chanlist[cname]->topic, "");
1317 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1318 chanlist[cname]->topicset = 0;
1319 Ptr = chanlist[cname];
1320 log(DEBUG,"add_channel: created: %s",cname);
1321 /* set created to 2 to indicate user
1322 * is the first in the channel
1323 * and should be given ops */
1329 /* channel exists, just fish out a pointer to its struct */
1330 Ptr = FindChan(cname);
1333 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1335 // the override flag allows us to bypass channel modes
1336 // and bans (used by servers)
1339 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1344 if (strcmp(Ptr->key,""))
1346 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1349 log(DEBUG,"add_channel: no key given in JOIN");
1350 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1355 log(DEBUG,"key at %p is %s",key,key);
1356 if (strcasecmp(key,Ptr->key))
1358 log(DEBUG,"add_channel: bad key given in JOIN");
1359 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1364 log(DEBUG,"add_channel: no key");
1366 if (Ptr->inviteonly)
1368 log(DEBUG,"add_channel: channel is +i");
1369 if (user->IsInvited(Ptr->name))
1371 /* user was invited to channel */
1372 /* there may be an optional channel NOTICE here */
1376 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1380 log(DEBUG,"add_channel: channel is not +i");
1384 if (usercount(Ptr) == Ptr->limit)
1386 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1391 log(DEBUG,"add_channel: about to walk banlist");
1393 /* check user against the channel banlist */
1396 if (Ptr->bans.size())
1398 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1400 if (match(user->GetFullHost(),i->data))
1402 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1409 log(DEBUG,"add_channel: bans checked");
1412 if ((Ptr) && (user))
1414 user->RemoveInvite(Ptr->name);
1417 log(DEBUG,"add_channel: invites removed");
1422 log(DEBUG,"Overridden checks");
1430 log(DEBUG,"Passed channel checks");
1432 for (int i =0; i != MAXCHANS; i++)
1434 log(DEBUG,"Check location %d",i);
1435 if (user->chans[i].channel == NULL)
1437 log(DEBUG,"Adding into their channel list at location %d",i);
1441 /* first user in is given ops */
1442 user->chans[i].uc_modes = UCMODE_OP;
1446 user->chans[i].uc_modes = 0;
1448 user->chans[i].channel = Ptr;
1449 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1451 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1453 // use the stamdard J token with no privilages.
1454 char buffer[MAXBUF];
1455 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1456 NetSendToAll(buffer);
1459 log(DEBUG,"Sent JOIN to client");
1463 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1464 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1467 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1468 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1469 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1470 FOREACH_MOD OnUserJoin(user,Ptr);
1474 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1475 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1479 /* remove a channel from a users record, and remove the record from memory
1480 * if the channel has become empty */
1482 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1484 if ((!user) || (!cname))
1486 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1493 if ((!cname) || (!user))
1498 Ptr = FindChan(cname);
1505 FOREACH_MOD OnUserPart(user,Ptr);
1506 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1508 for (int i =0; i != MAXCHANS; i++)
1510 /* zap it from the channel list of the user */
1511 if (user->chans[i].channel == Ptr)
1515 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1519 char buffer[MAXBUF];
1520 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1521 NetSendToAll(buffer);
1530 char buffer[MAXBUF];
1531 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1532 NetSendToAll(buffer);
1535 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1537 user->chans[i].uc_modes = 0;
1538 user->chans[i].channel = NULL;
1539 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1544 /* if there are no users left on the channel */
1545 if (!usercount(Ptr))
1547 chan_hash::iterator iter = chanlist.find(Ptr->name);
1549 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1551 /* kill the record */
1552 if (iter != chanlist.end())
1554 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1555 delete iter->second;
1556 chanlist.erase(iter);
1562 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1564 if ((!src) || (!user) || (!Ptr) || (!reason))
1566 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1573 if ((!Ptr) || (!user) || (!src))
1578 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1580 if (!has_channel(user,Ptr))
1582 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1585 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1587 if (cstatus(src,Ptr) == STATUS_HOP)
1589 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1593 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1599 for (int i =0; i != MAXCHANS; i++)
1601 /* zap it from the channel list of the user */
1602 if (user->chans[i].channel)
1603 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1605 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1606 user->chans[i].uc_modes = 0;
1607 user->chans[i].channel = NULL;
1608 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1613 /* if there are no users left on the channel */
1614 if (!usercount(Ptr))
1616 chan_hash::iterator iter = chanlist.find(Ptr->name);
1618 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1620 /* kill the record */
1621 if (iter != chanlist.end())
1623 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1624 delete iter->second;
1625 chanlist.erase(iter);
1633 /* This function pokes and hacks at a parameter list like the following:
1635 * PART #winbot, #darkgalaxy :m00!
1637 * to turn it into a series of individual calls like this:
1639 * PART #winbot :m00!
1640 * PART #darkgalaxy :m00!
1642 * The seperate calls are sent to a callback function provided by the caller
1643 * (the caller will usually call itself recursively). The callback function
1644 * must be a command handler. Calling this function on a line with no list causes
1645 * no action to be taken. You must provide a starting and ending parameter number
1646 * where the range of the list can be found, useful if you have a terminating
1647 * parameter as above which is actually not part of the list, or parameters
1648 * before the actual list as well. This code is used by many functions which
1649 * can function as "one to list" (see the RFC) */
1651 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1656 char blog[32][MAXBUF];
1657 char blog2[32][MAXBUF];
1658 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1659 char keystr[MAXBUF];
1662 for (int i = 0; i <32; i++)
1665 for (int i = 0; i <32; i++)
1666 strcpy(blog2[i],"");
1669 for (int i = 0; i <10; i++)
1673 parameters[i] = moo;
1678 if (pcnt > 1) /* we have a key to copy */
1680 strcpy(keystr,parameters[1]);
1684 if (!parameters[start])
1688 if (!strchr(parameters[start],','))
1693 for (int i = start; i <= end; i++)
1697 strcat(plist,parameters[i]);
1705 for (int i = 0; i < t; i++)
1707 if (plist[i] == ',')
1710 strcpy(blog[j++],param);
1714 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1719 strcpy(blog[j++],param);
1722 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1727 if ((joins) && (keystr))
1729 if (strchr(keystr,','))
1733 t2 = strlen(keystr);
1734 for (int i = 0; i < t2; i++)
1736 if (keystr[i] == ',')
1739 strcpy(blog2[j++],param);
1743 strcpy(blog2[j++],param);
1748 for (j = 0; j < total; j++)
1754 for (q = end; q < pcnt-1; q++)
1756 if (parameters[q+1])
1758 pars[q-end+1] = parameters[q+1];
1761 if ((joins) && (parameters[1]))
1772 /* repeatedly call the function with the hacked parameter list */
1773 if ((joins) && (pcnt > 1))
1777 // pars[1] already set up and containing key from blog2[j]
1782 pars[1] = parameters[1];
1788 fn(pars,pcnt-(end-start),u);
1797 void kill_link(userrec *user,const char* r)
1799 user_hash::iterator iter = clientlist.find(user->nick);
1801 char reason[MAXBUF];
1803 strncpy(reason,r,MAXBUF);
1805 if (strlen(reason)>MAXQUIT)
1807 reason[MAXQUIT-1] = '\0';
1810 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1811 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1812 log(DEBUG,"closing fd %d",user->fd);
1814 /* bugfix, cant close() a nonblocking socket (sux!) */
1815 if (user->registered == 7) {
1816 FOREACH_MOD OnUserQuit(user);
1817 WriteCommonExcept(user,"QUIT :%s",reason);
1819 // Q token must go to ALL servers!!!
1820 char buffer[MAXBUF];
1821 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1822 NetSendToAll(buffer);
1825 /* push the socket on a stack of sockets due to be closed at the next opportunity
1826 * 'Client exited' is an exception to this as it means the client side has already
1827 * closed the socket, we don't need to do it.
1829 fd_reap.push_back(user->fd);
1831 bool do_purge = false;
1833 if (user->registered == 7) {
1834 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1838 if (iter != clientlist.end())
1840 log(DEBUG,"deleting user hash value %d",iter->second);
1841 if ((iter->second) && (user->registered == 7)) {
1842 delete iter->second;
1844 clientlist.erase(iter);
1847 if (user->registered == 7) {
1848 purge_empty_chans();
1852 void kill_link_silent(userrec *user,const char* r)
1854 user_hash::iterator iter = clientlist.find(user->nick);
1856 char reason[MAXBUF];
1858 strncpy(reason,r,MAXBUF);
1860 if (strlen(reason)>MAXQUIT)
1862 reason[MAXQUIT-1] = '\0';
1865 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1866 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1867 log(DEBUG,"closing fd %d",user->fd);
1869 /* bugfix, cant close() a nonblocking socket (sux!) */
1870 if (user->registered == 7) {
1871 FOREACH_MOD OnUserQuit(user);
1872 WriteCommonExcept(user,"QUIT :%s",reason);
1874 // Q token must go to ALL servers!!!
1875 char buffer[MAXBUF];
1876 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1877 NetSendToAll(buffer);
1880 /* push the socket on a stack of sockets due to be closed at the next opportunity
1881 * 'Client exited' is an exception to this as it means the client side has already
1882 * closed the socket, we don't need to do it.
1884 fd_reap.push_back(user->fd);
1886 bool do_purge = false;
1888 if (iter != clientlist.end())
1890 log(DEBUG,"deleting user hash value %d",iter->second);
1891 if ((iter->second) && (user->registered == 7)) {
1892 delete iter->second;
1894 clientlist.erase(iter);
1897 if (user->registered == 7) {
1898 purge_empty_chans();
1904 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1906 char* Passwd(userrec *user)
1908 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1910 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1918 bool IsDenied(userrec *user)
1920 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1922 if (match(user->host,i->host) && (i->type == CC_DENY))
1933 /* sends out an error notice to all connected clients (not to be used
1936 void send_error(char *s)
1938 log(DEBUG,"send_error: %s",s);
1939 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1941 if (isnick(i->second->nick))
1943 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1947 // fix - unregistered connections receive ERROR, not NOTICE
1948 Write(i->second->fd,"ERROR :%s",s);
1953 void Error(int status)
1955 signal (SIGALRM, SIG_IGN);
1956 signal (SIGPIPE, SIG_IGN);
1957 signal (SIGTERM, SIG_IGN);
1958 signal (SIGABRT, SIG_IGN);
1959 signal (SIGSEGV, SIG_IGN);
1960 signal (SIGURG, SIG_IGN);
1961 signal (SIGKILL, SIG_IGN);
1962 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1963 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1968 int main(int argc, char *argv[])
1972 log(DEBUG,"*** InspIRCd starting up!");
1973 if (!FileExists(CONFIG_FILE))
1975 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1976 log(DEBUG,"main: no config");
1977 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1981 if (!strcmp(argv[1],"-nofork")) {
1985 if (InspIRCd() == ERROR)
1987 log(DEBUG,"main: daemon function bailed");
1988 printf("ERROR: could not initialise. Shutting down.\n");
1995 template<typename T> inline string ConvToStr(const T &in)
1998 if (!(tmp << in)) return string();
2002 /* re-allocates a nick in the user_hash after they change nicknames,
2003 * returns a pointer to the new user as it may have moved */
2005 userrec* ReHashNick(char* Old, char* New)
2007 user_hash::iterator newnick;
2008 user_hash::iterator oldnick = clientlist.find(Old);
2010 log(DEBUG,"ReHashNick: %s %s",Old,New);
2012 if (!strcasecmp(Old,New))
2014 log(DEBUG,"old nick is new nick, skipping");
2015 return oldnick->second;
2018 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2020 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2022 clientlist[New] = new userrec();
2023 clientlist[New] = oldnick->second;
2024 /*delete oldnick->second; */
2025 clientlist.erase(oldnick);
2027 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2029 return clientlist[New];
2032 /* adds or updates an entry in the whowas list */
2033 void AddWhoWas(userrec* u)
2035 user_hash::iterator iter = whowas.find(u->nick);
2036 userrec *a = new userrec();
2037 strcpy(a->nick,u->nick);
2038 strcpy(a->ident,u->ident);
2039 strcpy(a->dhost,u->dhost);
2040 strcpy(a->host,u->host);
2041 strcpy(a->fullname,u->fullname);
2042 strcpy(a->server,u->server);
2043 a->signon = u->signon;
2045 /* MAX_WHOWAS: max number of /WHOWAS items
2046 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2047 * can be replaced by a newer one
2050 if (iter == whowas.end())
2052 if (whowas.size() == WHOWAS_MAX)
2054 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2056 // 3600 seconds in an hour ;)
2057 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2061 log(DEBUG,"added WHOWAS entry, purged an old record");
2068 log(DEBUG,"added fresh WHOWAS entry");
2069 whowas[a->nick] = a;
2074 log(DEBUG,"updated WHOWAS entry");
2075 delete iter->second;
2081 /* add a client connection to the sockets list */
2082 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2086 char resolved[MAXBUF];
2089 user_hash::iterator iter;
2091 tempnick = ConvToStr(socket) + "-unknown";
2092 sprintf(tn2,"%d-unknown",socket);
2094 iter = clientlist.find(tempnick);
2096 if (iter != clientlist.end()) return;
2099 * It is OK to access the value here this way since we know
2100 * it exists, we just created it above.
2102 * At NO other time should you access a value in a map or a
2103 * hash_map this way.
2105 clientlist[tempnick] = new userrec();
2107 NonBlocking(socket);
2108 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2110 clientlist[tempnick]->fd = socket;
2111 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2112 strncpy(clientlist[tempnick]->host, host,160);
2113 strncpy(clientlist[tempnick]->dhost, host,160);
2114 strncpy(clientlist[tempnick]->server, ServerName,256);
2115 strncpy(clientlist[tempnick]->ident, "unknown",9);
2116 clientlist[tempnick]->registered = 0;
2117 clientlist[tempnick]->signon = time(NULL);
2118 clientlist[tempnick]->nping = time(NULL)+240;
2119 clientlist[tempnick]->lastping = 1;
2120 clientlist[tempnick]->port = port;
2121 strncpy(clientlist[tempnick]->ip,ip,32);
2125 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2129 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2132 // set the registration timeout for this user
2133 unsigned long class_regtimeout = 90;
2134 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2136 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2138 class_regtimeout = (unsigned long)i->registration_timeout;
2143 int class_flood = 0;
2144 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2146 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2148 class_flood = i->flood;
2153 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2154 clientlist[tempnick]->flood = class_flood;
2156 for (int i = 0; i < MAXCHANS; i++)
2158 clientlist[tempnick]->chans[i].channel = NULL;
2159 clientlist[tempnick]->chans[i].uc_modes = 0;
2162 if (clientlist.size() == MAXCLIENTS)
2163 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2165 char* r = matches_zline(ip);
2168 char reason[MAXBUF];
2169 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2170 kill_link(clientlist[tempnick],reason);
2177 return clientlist.size();
2181 int usercount_invisible(void)
2185 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2187 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2192 int usercount_opers(void)
2196 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2198 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2203 int usercount_unknown(void)
2207 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2209 if ((i->second->fd) && (i->second->registered != 7))
2215 long chancount(void)
2217 return chanlist.size();
2220 long count_servs(void)
2223 //for (int j = 0; j < 255; j++)
2225 // if (servers[j] != NULL)
2231 long servercount(void)
2233 return count_servs()+1;
2239 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2241 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2247 void ShowMOTD(userrec *user)
2251 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2254 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2255 for (int i = 0; i != MOTD.size(); i++)
2257 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2259 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2262 void ShowRULES(userrec *user)
2266 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2269 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2270 for (int i = 0; i != RULES.size(); i++)
2272 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2274 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2277 /* shows the message of the day, and any other on-logon stuff */
2278 void ConnectUser(userrec *user)
2280 user->registered = 7;
2281 user->idle_lastmsg = time(NULL);
2282 log(DEBUG,"ConnectUser: %s",user->nick);
2284 if (strcmp(Passwd(user),"") && (!user->haspassed))
2286 kill_link(user,"Invalid password");
2291 kill_link(user,"Unauthorised connection");
2295 char match_against[MAXBUF];
2296 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2297 char* r = matches_gline(match_against);
2300 char reason[MAXBUF];
2301 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2302 kill_link_silent(user,reason);
2306 r = matches_kline(user->host);
2309 char reason[MAXBUF];
2310 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2311 kill_link_silent(user,reason);
2315 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2316 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2317 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2318 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2319 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2320 WriteServ(user->fd,"005 %s MAP KNOCK SAFELIST HCN MAXCHANNELS=20 MAXBANS=60 NICKLEN=30 TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 :are supported by this server",user->nick);
2321 WriteServ(user->fd,"005 %s WALLCHOPS WATCH=128 SILENCE=5 MODES=13 CHANTYPES=# PREFIX=(ohv)@%c+ CHANMODES=ohvbeqa,kfL,l,psmntirRcOAQKVHGCuzN NETWORK=%s :are supported by this server",user->nick,'%',Network);
2323 FOREACH_MOD OnUserConnect(user);
2324 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2326 char buffer[MAXBUF];
2327 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);
2328 NetSendToAll(buffer);
2331 void handle_version(char **parameters, int pcnt, userrec *user)
2333 char Revision[] = "$Revision$";
2335 char *s1 = Revision;
2337 char *v1 = strtok_r(s1," ",&savept);
2339 char *v2 = strtok_r(s1," ",&savept);
2342 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2346 // calls a handler function for a command
2348 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2350 for (int i = 0; i < cmdlist.size(); i++)
2352 if (!strcasecmp(cmdlist[i].command,commandname))
2354 if (cmdlist[i].handler_function)
2356 if (pcnt>=cmdlist[i].min_params)
2358 if (strchr(user->modes,cmdlist[i].flags_needed))
2360 cmdlist[i].handler_function(parameters,pcnt,user);
2368 void DoSplitEveryone()
2370 bool go_again = true;
2374 for (int i = 0; i < 32; i++)
2378 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2380 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2383 j->CloseConnection();
2384 me[i]->connectors.erase(j);
2392 log(DEBUG,"Removed server. Will remove clients...");
2393 // iterate through the userlist and remove all users on this server.
2394 // because we're dealing with a mesh, we dont have to deal with anything
2395 // "down-route" from this server (nice huh)
2397 char reason[MAXBUF];
2401 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2403 if (strcasecmp(u->second->server,ServerName))
2405 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2406 kill_link(u->second,reason);
2416 char islast(const char* s)
2419 for (int j = 0; j < 32; j++)
2423 for (int k = 0; k < me[j]->connectors.size(); k++)
2425 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2429 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2439 long map_count(const char* s)
2442 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2444 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2450 void force_nickchange(userrec* user,const char* newnick)
2457 FOREACH_RESULT(OnUserPreNick(user,newnick));
2459 kill_link(user,"Nickname collision");
2462 if (matches_qline(newnick))
2464 kill_link(user,"Nickname collision");
2472 strncpy(nick,newnick,MAXBUF);
2474 if (user->registered == 7)
2478 handle_nick(pars,1,user);
2484 int process_parameters(char **command_p,char *parameters)
2489 q = strlen(parameters);
2492 /* no parameters, command_p invalid! */
2495 if (parameters[0] == ':')
2497 command_p[0] = parameters+1;
2502 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2504 /* only one parameter */
2505 command_p[0] = parameters;
2506 if (parameters[0] == ':')
2508 if (strchr(parameters,' ') != NULL)
2516 command_p[j++] = parameters;
2517 for (int i = 0; i <= q; i++)
2519 if (parameters[i] == ' ')
2521 command_p[j++] = parameters+i+1;
2522 parameters[i] = '\0';
2523 if (command_p[j-1][0] == ':')
2525 *command_p[j-1]++; /* remove dodgy ":" */
2527 /* parameter like this marks end of the sequence */
2531 return j; /* returns total number of items in the list */
2534 void process_command(userrec *user, char* cmd)
2538 char *command_p[127];
2539 char p[MAXBUF], temp[MAXBUF];
2540 int i, j, items, cmd_found;
2542 for (int i = 0; i < 127; i++)
2543 command_p[i] = NULL;
2553 if (!strcmp(cmd,""))
2558 int total_params = 0;
2561 for (int q = 0; q < strlen(cmd)-1; q++)
2563 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2566 // found a 'trailing', we dont count them after this.
2574 // another phidjit bug...
2575 if (total_params > 126)
2577 kill_link(user,"Protocol violation (1)");
2583 std::string tmp = cmd;
2584 for (int i = 0; i <= MODCOUNT; i++)
2586 std::string oldtmp = tmp;
2587 modules[i]->OnServerRaw(tmp,true);
2590 log(DEBUG,"A Module changed the input string!");
2591 log(DEBUG,"New string: %s",tmp.c_str());
2592 log(DEBUG,"Old string: %s",oldtmp.c_str());
2596 strncpy(cmd,tmp.c_str(),MAXBUF);
2599 if (!strchr(cmd,' '))
2601 /* no parameters, lets skip the formalities and not chop up
2603 log(DEBUG,"About to preprocess command with no params");
2605 command_p[0] = NULL;
2607 for (int i = 0; i <= strlen(cmd); i++)
2609 cmd[i] = toupper(cmd[i]);
2611 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2618 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2619 for (int i = 0; i < strlen(temp); i++)
2621 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2627 /* split the full string into a command plus parameters */
2631 if (strchr(cmd,' '))
2633 for (int i = 0; i <= strlen(cmd); i++)
2635 /* capitalise the command ONLY, leave params intact */
2636 cmd[i] = toupper(cmd[i]);
2637 /* are we nearly there yet?! :P */
2641 parameters = cmd+i+1;
2649 for (int i = 0; i <= strlen(cmd); i++)
2651 cmd[i] = toupper(cmd[i]);
2658 if (strlen(command)>MAXCOMMAND)
2660 kill_link(user,"Protocol violation (2)");
2664 for (int x = 0; x < strlen(command); x++)
2666 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2668 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2670 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2672 kill_link(user,"Protocol violation (3)");
2679 for (int i = 0; i != cmdlist.size(); i++)
2681 if (strcmp(cmdlist[i].command,""))
2683 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2685 log(DEBUG,"Found matching command");
2689 if (strcmp(parameters,""))
2691 items = process_parameters(command_p,parameters);
2696 command_p[0] = NULL;
2702 command_p[0] = NULL;
2707 log(DEBUG,"Processing command");
2709 /* activity resets the ping pending timer */
2710 user->nping = time(NULL) + 120;
2711 if ((items) < cmdlist[i].min_params)
2713 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2714 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2717 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2719 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2720 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2724 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2726 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2728 if ((!isnick(user->nick)) || (user->registered != 7))
2730 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2731 WriteServ(user->fd,"451 %s :You have not registered",command);
2735 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2737 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2738 if (cmdlist[i].handler_function)
2740 /* ikky /stats counters */
2745 user->bytes_in += strlen(temp);
2748 cmdlist[i].use_count++;
2749 cmdlist[i].total_bytes+=strlen(temp);
2752 /* WARNING: nothing may come after the
2753 * command handler call, as the handler
2754 * may free the user structure! */
2756 cmdlist[i].handler_function(command_p,items,user);
2762 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2763 WriteServ(user->fd,"451 %s :You have not registered",command);
2771 if ((!cmd_found) && (user))
2773 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2774 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2779 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2782 /* create the command and push it onto the table */
2783 strcpy(comm.command,cmd);
2784 comm.handler_function = f;
2785 comm.flags_needed = flags;
2786 comm.min_params = minparams;
2788 comm.total_bytes = 0;
2789 cmdlist.push_back(comm);
2790 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2793 void SetupCommandTable(void)
2795 createcommand("USER",handle_user,0,4);
2796 createcommand("NICK",handle_nick,0,1);
2797 createcommand("QUIT",handle_quit,0,0);
2798 createcommand("VERSION",handle_version,0,0);
2799 createcommand("PING",handle_ping,0,1);
2800 createcommand("PONG",handle_pong,0,1);
2801 createcommand("ADMIN",handle_admin,0,0);
2802 createcommand("PRIVMSG",handle_privmsg,0,2);
2803 createcommand("INFO",handle_info,0,0);
2804 createcommand("TIME",handle_time,0,0);
2805 createcommand("WHOIS",handle_whois,0,1);
2806 createcommand("WALLOPS",handle_wallops,'o',1);
2807 createcommand("NOTICE",handle_notice,0,2);
2808 createcommand("JOIN",handle_join,0,1);
2809 createcommand("NAMES",handle_names,0,1);
2810 createcommand("PART",handle_part,0,1);
2811 createcommand("KICK",handle_kick,0,2);
2812 createcommand("MODE",handle_mode,0,1);
2813 createcommand("TOPIC",handle_topic,0,1);
2814 createcommand("WHO",handle_who,0,1);
2815 createcommand("MOTD",handle_motd,0,0);
2816 createcommand("RULES",handle_rules,0,0);
2817 createcommand("OPER",handle_oper,0,2);
2818 createcommand("LIST",handle_list,0,0);
2819 createcommand("DIE",handle_die,'o',1);
2820 createcommand("RESTART",handle_restart,'o',1);
2821 createcommand("KILL",handle_kill,'o',2);
2822 createcommand("REHASH",handle_rehash,'o',0);
2823 createcommand("LUSERS",handle_lusers,0,0);
2824 createcommand("STATS",handle_stats,0,1);
2825 createcommand("USERHOST",handle_userhost,0,1);
2826 createcommand("AWAY",handle_away,0,0);
2827 createcommand("ISON",handle_ison,0,0);
2828 createcommand("SUMMON",handle_summon,0,0);
2829 createcommand("USERS",handle_users,0,0);
2830 createcommand("INVITE",handle_invite,0,2);
2831 createcommand("PASS",handle_pass,0,1);
2832 createcommand("TRACE",handle_trace,'o',0);
2833 createcommand("WHOWAS",handle_whowas,0,1);
2834 createcommand("CONNECT",handle_connect,'o',1);
2835 createcommand("SQUIT",handle_squit,'o',0);
2836 createcommand("MODULES",handle_modules,'o',0);
2837 createcommand("LINKS",handle_links,0,0);
2838 createcommand("MAP",handle_map,0,0);
2839 createcommand("KLINE",handle_kline,'o',1);
2840 createcommand("GLINE",handle_gline,'o',1);
2841 createcommand("ZLINE",handle_zline,'o',1);
2842 createcommand("QLINE",handle_qline,'o',1);
2845 void process_buffer(const char* cmdbuf,userrec *user)
2849 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2856 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2859 if (!strcmp(cmdbuf,""))
2863 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2865 strncpy(cmd,cmdbuf,MAXBUF);
2866 if (!strcmp(cmd,""))
2870 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2872 cmd[strlen(cmd)-1] = '\0';
2874 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2876 cmd[strlen(cmd)-1] = '\0';
2879 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2881 cmd[strlen(cmd)-1] = '\0';
2884 if (!strcmp(cmd,""))
2888 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2890 if ((user) && (cmd))
2892 process_command(user,cmd);
2896 void DoSync(serverrec* serv, char* tcp_host)
2899 log(DEBUG,"Sending sync");
2900 // send start of sync marker: Y <timestamp>
2901 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2902 // except the ones its receiving it from.
2903 snprintf(data,MAXBUF,"Y %d",time(NULL));
2904 serv->SendPacket(data,tcp_host);
2905 // send users and channels
2906 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2908 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);
2909 serv->SendPacket(data,tcp_host);
2910 if (strcmp(chlist(u->second),""))
2912 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2913 serv->SendPacket(data,tcp_host);
2916 // send channel modes, topics etc...
2917 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2919 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2920 serv->SendPacket(data,tcp_host);
2921 if (strcmp(c->second->topic,""))
2923 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2924 serv->SendPacket(data,tcp_host);
2926 // send current banlist
2928 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2930 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2931 serv->SendPacket(data,tcp_host);
2934 // sync global zlines, glines, etc
2935 sync_xlines(serv,tcp_host);
2936 snprintf(data,MAXBUF,"F %d",time(NULL));
2937 serv->SendPacket(data,tcp_host);
2938 log(DEBUG,"Sent sync");
2939 // ircd sends its serverlist after the end of sync here
2943 void NetSendMyRoutingTable()
2945 // send out a line saying what is reachable to us.
2946 // E.g. if A is linked to B C and D, send out:
2948 // if its only linked to B and D send out:
2950 // if it has no links, dont even send out the line at all.
2951 char buffer[MAXBUF];
2952 sprintf(buffer,"$ %s",ServerName);
2953 bool sendit = false;
2954 for (int i = 0; i < 32; i++)
2958 for (int j = 0; j < me[i]->connectors.size(); j++)
2960 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2962 strncat(buffer," ",MAXBUF);
2963 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2970 NetSendToAll(buffer);
2974 void DoSplit(const char* params)
2976 bool go_again = true;
2980 for (int i = 0; i < 32; i++)
2984 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2986 if (!strcasecmp(j->GetServerName().c_str(),params))
2989 j->CloseConnection();
2990 me[i]->connectors.erase(j);
2998 log(DEBUG,"Removed server. Will remove clients...");
2999 // iterate through the userlist and remove all users on this server.
3000 // because we're dealing with a mesh, we dont have to deal with anything
3001 // "down-route" from this server (nice huh)
3003 char reason[MAXBUF];
3004 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3008 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3010 if (!strcasecmp(u->second->server,params))
3012 kill_link(u->second,reason);
3020 // removes a server. Will NOT remove its users!
3022 void RemoveServer(const char* name)
3024 bool go_again = true;
3028 for (int i = 0; i < 32; i++)
3032 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3034 if (!strcasecmp(j->GetServerName().c_str(),name))
3037 j->CloseConnection();
3038 me[i]->connectors.erase(j);
3049 int reap_counter = 0;
3053 struct sockaddr_in client, server;
3054 char addrs[MAXBUF][255];
3055 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3057 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3058 int selectResult = 0, selectResult2 = 0;
3059 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3060 char resolvedHost[MAXBUF];
3064 log_file = fopen("ircd.log","a+");
3067 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3071 log(DEBUG,"InspIRCd: startup: begin");
3075 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3077 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3079 SetupCommandTable();
3080 log(DEBUG,"InspIRCd: startup: default command table set up");
3083 if (strcmp(DieValue,""))
3085 printf("WARNING: %s\n\n",DieValue);
3088 log(DEBUG,"InspIRCd: startup: read config");
3090 int count2 = 0, count3 = 0;
3092 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3094 ConfValue("bind","port",count,configToken,&config_f);
3095 ConfValue("bind","address",count,Addr,&config_f);
3096 ConfValue("bind","type",count,Type,&config_f);
3097 if (!strcmp(Type,"servers"))
3099 char Default[MAXBUF];
3100 strcpy(Default,"no");
3101 ConfValue("bind","default",count,Default,&config_f);
3102 if (strchr(Default,'y'))
3104 defaultRoute = count3;
3105 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3107 me[count3] = new serverrec(ServerName,100L,false);
3108 me[count3]->CreateListener(Addr,atoi(configToken));
3113 ports[count2] = atoi(configToken);
3114 strcpy(addrs[count2],Addr);
3117 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3120 UDPportCount = count3;
3122 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3124 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3128 /* BugFix By Craig! :p */
3130 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3132 char modfile[MAXBUF];
3133 ConfValue("module","name",count2,configToken,&config_f);
3134 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3135 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3136 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3137 /* If The File Doesnt exist, Trying to load it
3138 * Will Segfault the IRCd.. So, check to see if
3139 * it Exists, Before Proceeding. */
3140 if (FileExists(modfile))
3142 factory[count] = new ircd_module(modfile);
3143 if (factory[count]->LastError())
3145 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3146 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3149 if (factory[count]->factory)
3151 modules[count] = factory[count]->factory->CreateModule();
3152 /* save the module and the module's classfactory, if
3153 * this isnt done, random crashes can occur :/ */
3154 module_names.push_back(modfile);
3158 log(DEBUG,"Unable to load %s",modfile);
3159 sprintf("Unable to load %s\nExiting...\n",modfile);
3162 /* Increase the Count */
3167 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3168 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3171 MODCOUNT = count - 1;
3172 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3174 printf("\nInspIRCd is now running!\n");
3176 startup_time = time(NULL);
3180 log(VERBOSE,"Not forking as -nofork was specified");
3184 if (DaemonSeed() == ERROR)
3186 log(DEBUG,"InspIRCd: startup: can't daemonise");
3187 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3193 /* setup select call */
3194 FD_ZERO(&selectFds);
3195 log(DEBUG,"InspIRCd: startup: zero selects");
3196 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3198 for (count = 0; count < portCount; count++)
3200 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3202 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3205 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3207 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3209 else /* well we at least bound to one socket so we'll continue */
3215 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3217 /* if we didn't bind to anything then abort */
3218 if (boundPortCount == 0)
3220 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3225 length = sizeof (client);
3226 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3228 /* main loop, this never returns */
3231 #ifdef _POSIX_PRIORITY_SCHEDULING
3234 // update the status of klines, etc
3241 user_hash::iterator count2 = clientlist.begin();
3243 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3244 // them in a list, then reap the list every second or so.
3245 if (reap_counter>300)
3247 if (fd_reap.size() > 0)
3249 for( int n = 0; n < fd_reap.size(); n++)
3251 Blocking(fd_reap[n]);
3253 NonBlocking(fd_reap[n]);
3262 FD_ZERO(&serverfds);
3265 for (int x = 0; x != UDPportCount; x++)
3267 FD_SET(me[x]->fd, &serverfds);
3273 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3276 for (int x = 0; x != UDPportCount; x++)
3278 if (FD_ISSET (me[x]->fd, &serverfds))
3280 char remotehost[MAXBUF],resolved[MAXBUF];
3281 length = sizeof (client);
3282 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3283 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3284 if(CleanAndResolve(resolved, remotehost) != TRUE)
3286 strncpy(resolved,remotehost,MAXBUF);
3288 // add to this connections ircd_connector vector
3289 // *FIX* - we need the LOCAL port not the remote port in &client!
3290 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3295 for (int x = 0; x < UDPportCount; x++)
3297 std::deque<std::string> msgs;
3299 if (me[x]->RecvPacket(msgs, tcp_host))
3301 for (int ctr = 0; ctr < msgs.size(); ctr++)
3303 char udp_msg[MAXBUF];
3304 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3305 if (strlen(udp_msg)<1)
3307 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3310 // during a netburst, send all data to all other linked servers
3311 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3313 if (is_uline(tcp_host))
3315 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3317 NetSendToAllExcept(tcp_host,udp_msg);
3321 NetSendToAllExcept(tcp_host,udp_msg);
3323 FOREACH_MOD OnPacketReceive(udp_msg);
3324 handle_link_packet(udp_msg, tcp_host, me[x]);
3331 while (count2 != clientlist.end())
3334 tval.tv_usec = tval.tv_sec = 0;
3336 int total_in_this_set = 0;
3338 user_hash::iterator xcount = count2;
3339 user_hash::iterator endingiter = count2;
3341 if (!count2->second) break;
3344 if (count2->second->fd != 0)
3346 // assemble up to 64 sockets into an fd_set
3347 // to implement a pooling mechanism.
3349 // This should be up to 64x faster than the
3350 // old implementation.
3351 while (total_in_this_set < 64)
3353 if (count2 != clientlist.end())
3355 // we don't check the state of remote users.
3356 if (count2->second->fd > 0)
3358 FD_SET (count2->second->fd, &sfd);
3360 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3361 // their connection class.
3362 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3364 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3365 kill_link(count2->second,"Registration timeout");
3368 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3370 if ((!count2->second->lastping) && (count2->second->registered == 7))
3372 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3373 kill_link(count2->second,"Ping timeout");
3376 Write(count2->second->fd,"PING :%s",ServerName);
3377 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3378 count2->second->lastping = 0;
3379 count2->second->nping = time(NULL)+120;
3383 total_in_this_set++;
3388 endingiter = count2;
3389 count2 = xcount; // roll back to where we were
3395 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3397 // now loop through all of the items in this pool if any are waiting
3398 //if (selectResult2 > 0)
3399 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3402 #ifdef _POSIX_PRIORITY_SCHEDULING
3407 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3409 log(DEBUG,"Reading fd %d",count2a->second->fd);
3410 memset(data, 0, 10240);
3411 result = read(count2a->second->fd, data, 10240);
3416 log(DEBUG,"Read %d characters from socket",result);
3417 userrec* current = count2a->second;
3418 int currfd = current->fd;
3419 char* l = strtok(data,"\n");
3424 if ((floodlines > current->flood) && (current->flood != 0))
3426 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3427 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3428 kill_link(current,"Excess flood");
3431 char sanitized[NetBufferSize];
3432 memset(sanitized, 0, NetBufferSize);
3434 for (int pt = 0; pt < strlen(l); pt++)
3438 sanitized[ptt++] = l[pt];
3441 sanitized[ptt] = '\0';
3442 if (strlen(sanitized))
3446 // we're gonna re-scan to check if the nick is gone, after every
3447 // command - if it has, we're gonna bail
3448 bool find_again = false;
3449 process_buffer(sanitized,current);
3451 // look for the user's record in case it's changed
3452 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3454 if (c2->second->fd == currfd)
3456 // found again, update pointer
3457 current == c2->second;
3466 l = strtok(NULL,"\n");
3471 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3473 log(DEBUG,"killing: %s",count2a->second->nick);
3474 kill_link(count2a->second,strerror(errno));
3478 // result EAGAIN means nothing read
3479 if (result == EAGAIN)
3487 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3488 kill_link(count2a->second,"Client exited");
3489 // must bail here? kill_link removes the hash, corrupting the iterator
3490 log(DEBUG,"Bailing from client exit");
3494 else if (result > 0)
3499 for (int q = 0; q < total_in_this_set; q++)
3501 // there is no iterator += operator :(
3502 //if (count2 != clientlist.end())
3509 // set up select call
3510 for (count = 0; count < boundPortCount; count++)
3512 FD_SET (openSockfd[count], &selectFds);
3516 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3518 /* select is reporting a waiting socket. Poll them all to find out which */
3519 if (selectResult > 0)
3521 char target[MAXBUF], resolved[MAXBUF];
3522 for (count = 0; count < boundPortCount; count++)
3524 if (FD_ISSET (openSockfd[count], &selectFds))
3526 length = sizeof (client);
3527 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3529 address_cache::iterator iter = IP.find(client.sin_addr);
3530 bool iscached = false;
3531 if (iter == IP.end())
3533 /* ip isn't in cache, add it */
3534 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3535 if(CleanAndResolve(resolved, target) != TRUE)
3537 strncpy(resolved,target,MAXBUF);
3539 /* hostname now in 'target' */
3540 IP[client.sin_addr] = new string(resolved);
3541 /* hostname in cache */
3545 /* found ip (cached) */
3546 strncpy(resolved, iter->second->c_str(), MAXBUF);
3550 if (incomingSockfd < 0)
3552 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3553 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3557 AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3558 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3565 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3568 close (incomingSockfd);