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];
1457 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1461 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1463 NetSendToAll(buffer);
1466 log(DEBUG,"Sent JOIN to client");
1470 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1471 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1474 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1475 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1476 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1477 FOREACH_MOD OnUserJoin(user,Ptr);
1481 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1482 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1486 /* remove a channel from a users record, and remove the record from memory
1487 * if the channel has become empty */
1489 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1491 if ((!user) || (!cname))
1493 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1500 if ((!cname) || (!user))
1505 Ptr = FindChan(cname);
1512 FOREACH_MOD OnUserPart(user,Ptr);
1513 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1515 for (int i =0; i != MAXCHANS; i++)
1517 /* zap it from the channel list of the user */
1518 if (user->chans[i].channel == Ptr)
1522 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1526 char buffer[MAXBUF];
1527 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1528 NetSendToAll(buffer);
1537 char buffer[MAXBUF];
1538 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1539 NetSendToAll(buffer);
1542 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1544 user->chans[i].uc_modes = 0;
1545 user->chans[i].channel = NULL;
1546 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1551 /* if there are no users left on the channel */
1552 if (!usercount(Ptr))
1554 chan_hash::iterator iter = chanlist.find(Ptr->name);
1556 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1558 /* kill the record */
1559 if (iter != chanlist.end())
1561 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1562 delete iter->second;
1563 chanlist.erase(iter);
1569 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1571 if ((!src) || (!user) || (!Ptr) || (!reason))
1573 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1580 if ((!Ptr) || (!user) || (!src))
1585 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1587 if (!has_channel(user,Ptr))
1589 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1592 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1594 if (cstatus(src,Ptr) == STATUS_HOP)
1596 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1600 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1606 for (int i =0; i != MAXCHANS; i++)
1608 /* zap it from the channel list of the user */
1609 if (user->chans[i].channel)
1610 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1612 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1613 user->chans[i].uc_modes = 0;
1614 user->chans[i].channel = NULL;
1615 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1620 /* if there are no users left on the channel */
1621 if (!usercount(Ptr))
1623 chan_hash::iterator iter = chanlist.find(Ptr->name);
1625 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1627 /* kill the record */
1628 if (iter != chanlist.end())
1630 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1631 delete iter->second;
1632 chanlist.erase(iter);
1640 /* This function pokes and hacks at a parameter list like the following:
1642 * PART #winbot, #darkgalaxy :m00!
1644 * to turn it into a series of individual calls like this:
1646 * PART #winbot :m00!
1647 * PART #darkgalaxy :m00!
1649 * The seperate calls are sent to a callback function provided by the caller
1650 * (the caller will usually call itself recursively). The callback function
1651 * must be a command handler. Calling this function on a line with no list causes
1652 * no action to be taken. You must provide a starting and ending parameter number
1653 * where the range of the list can be found, useful if you have a terminating
1654 * parameter as above which is actually not part of the list, or parameters
1655 * before the actual list as well. This code is used by many functions which
1656 * can function as "one to list" (see the RFC) */
1658 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1663 char blog[32][MAXBUF];
1664 char blog2[32][MAXBUF];
1665 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1666 char keystr[MAXBUF];
1669 for (int i = 0; i <32; i++)
1672 for (int i = 0; i <32; i++)
1673 strcpy(blog2[i],"");
1676 for (int i = 0; i <10; i++)
1680 parameters[i] = moo;
1685 if (pcnt > 1) /* we have a key to copy */
1687 strcpy(keystr,parameters[1]);
1691 if (!parameters[start])
1695 if (!strchr(parameters[start],','))
1700 for (int i = start; i <= end; i++)
1704 strcat(plist,parameters[i]);
1712 for (int i = 0; i < t; i++)
1714 if (plist[i] == ',')
1717 strcpy(blog[j++],param);
1721 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1726 strcpy(blog[j++],param);
1729 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1734 if ((joins) && (keystr))
1736 if (strchr(keystr,','))
1740 t2 = strlen(keystr);
1741 for (int i = 0; i < t2; i++)
1743 if (keystr[i] == ',')
1746 strcpy(blog2[j++],param);
1750 strcpy(blog2[j++],param);
1755 for (j = 0; j < total; j++)
1761 for (q = end; q < pcnt-1; q++)
1763 if (parameters[q+1])
1765 pars[q-end+1] = parameters[q+1];
1768 if ((joins) && (parameters[1]))
1779 /* repeatedly call the function with the hacked parameter list */
1780 if ((joins) && (pcnt > 1))
1784 // pars[1] already set up and containing key from blog2[j]
1789 pars[1] = parameters[1];
1795 fn(pars,pcnt-(end-start),u);
1804 void kill_link(userrec *user,const char* r)
1806 user_hash::iterator iter = clientlist.find(user->nick);
1808 char reason[MAXBUF];
1810 strncpy(reason,r,MAXBUF);
1812 if (strlen(reason)>MAXQUIT)
1814 reason[MAXQUIT-1] = '\0';
1817 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1818 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1819 log(DEBUG,"closing fd %d",user->fd);
1821 /* bugfix, cant close() a nonblocking socket (sux!) */
1822 if (user->registered == 7) {
1823 FOREACH_MOD OnUserQuit(user);
1824 WriteCommonExcept(user,"QUIT :%s",reason);
1826 // Q token must go to ALL servers!!!
1827 char buffer[MAXBUF];
1828 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1829 NetSendToAll(buffer);
1832 /* push the socket on a stack of sockets due to be closed at the next opportunity
1833 * 'Client exited' is an exception to this as it means the client side has already
1834 * closed the socket, we don't need to do it.
1836 fd_reap.push_back(user->fd);
1838 bool do_purge = false;
1840 if (user->registered == 7) {
1841 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1845 if (iter != clientlist.end())
1847 log(DEBUG,"deleting user hash value %d",iter->second);
1848 if ((iter->second) && (user->registered == 7)) {
1849 delete iter->second;
1851 clientlist.erase(iter);
1854 if (user->registered == 7) {
1855 purge_empty_chans();
1859 void kill_link_silent(userrec *user,const char* r)
1861 user_hash::iterator iter = clientlist.find(user->nick);
1863 char reason[MAXBUF];
1865 strncpy(reason,r,MAXBUF);
1867 if (strlen(reason)>MAXQUIT)
1869 reason[MAXQUIT-1] = '\0';
1872 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1873 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1874 log(DEBUG,"closing fd %d",user->fd);
1876 /* bugfix, cant close() a nonblocking socket (sux!) */
1877 if (user->registered == 7) {
1878 FOREACH_MOD OnUserQuit(user);
1879 WriteCommonExcept(user,"QUIT :%s",reason);
1881 // Q token must go to ALL servers!!!
1882 char buffer[MAXBUF];
1883 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1884 NetSendToAll(buffer);
1887 /* push the socket on a stack of sockets due to be closed at the next opportunity
1888 * 'Client exited' is an exception to this as it means the client side has already
1889 * closed the socket, we don't need to do it.
1891 fd_reap.push_back(user->fd);
1893 bool do_purge = false;
1895 if (iter != clientlist.end())
1897 log(DEBUG,"deleting user hash value %d",iter->second);
1898 if ((iter->second) && (user->registered == 7)) {
1899 delete iter->second;
1901 clientlist.erase(iter);
1904 if (user->registered == 7) {
1905 purge_empty_chans();
1911 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1913 char* Passwd(userrec *user)
1915 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1917 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1925 bool IsDenied(userrec *user)
1927 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1929 if (match(user->host,i->host) && (i->type == CC_DENY))
1940 /* sends out an error notice to all connected clients (not to be used
1943 void send_error(char *s)
1945 log(DEBUG,"send_error: %s",s);
1946 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1948 if (isnick(i->second->nick))
1950 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1954 // fix - unregistered connections receive ERROR, not NOTICE
1955 Write(i->second->fd,"ERROR :%s",s);
1960 void Error(int status)
1962 signal (SIGALRM, SIG_IGN);
1963 signal (SIGPIPE, SIG_IGN);
1964 signal (SIGTERM, SIG_IGN);
1965 signal (SIGABRT, SIG_IGN);
1966 signal (SIGSEGV, SIG_IGN);
1967 signal (SIGURG, SIG_IGN);
1968 signal (SIGKILL, SIG_IGN);
1969 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1970 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1975 int main(int argc, char *argv[])
1979 log(DEBUG,"*** InspIRCd starting up!");
1980 if (!FileExists(CONFIG_FILE))
1982 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1983 log(DEBUG,"main: no config");
1984 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1988 if (!strcmp(argv[1],"-nofork")) {
1992 if (InspIRCd() == ERROR)
1994 log(DEBUG,"main: daemon function bailed");
1995 printf("ERROR: could not initialise. Shutting down.\n");
2002 template<typename T> inline string ConvToStr(const T &in)
2005 if (!(tmp << in)) return string();
2009 /* re-allocates a nick in the user_hash after they change nicknames,
2010 * returns a pointer to the new user as it may have moved */
2012 userrec* ReHashNick(char* Old, char* New)
2014 user_hash::iterator newnick;
2015 user_hash::iterator oldnick = clientlist.find(Old);
2017 log(DEBUG,"ReHashNick: %s %s",Old,New);
2019 if (!strcasecmp(Old,New))
2021 log(DEBUG,"old nick is new nick, skipping");
2022 return oldnick->second;
2025 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2027 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2029 clientlist[New] = new userrec();
2030 clientlist[New] = oldnick->second;
2031 /*delete oldnick->second; */
2032 clientlist.erase(oldnick);
2034 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2036 return clientlist[New];
2039 /* adds or updates an entry in the whowas list */
2040 void AddWhoWas(userrec* u)
2042 user_hash::iterator iter = whowas.find(u->nick);
2043 userrec *a = new userrec();
2044 strcpy(a->nick,u->nick);
2045 strcpy(a->ident,u->ident);
2046 strcpy(a->dhost,u->dhost);
2047 strcpy(a->host,u->host);
2048 strcpy(a->fullname,u->fullname);
2049 strcpy(a->server,u->server);
2050 a->signon = u->signon;
2052 /* MAX_WHOWAS: max number of /WHOWAS items
2053 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2054 * can be replaced by a newer one
2057 if (iter == whowas.end())
2059 if (whowas.size() == WHOWAS_MAX)
2061 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2063 // 3600 seconds in an hour ;)
2064 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2068 log(DEBUG,"added WHOWAS entry, purged an old record");
2075 log(DEBUG,"added fresh WHOWAS entry");
2076 whowas[a->nick] = a;
2081 log(DEBUG,"updated WHOWAS entry");
2082 delete iter->second;
2088 /* add a client connection to the sockets list */
2089 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2093 char resolved[MAXBUF];
2096 user_hash::iterator iter;
2098 tempnick = ConvToStr(socket) + "-unknown";
2099 sprintf(tn2,"%d-unknown",socket);
2101 iter = clientlist.find(tempnick);
2103 if (iter != clientlist.end()) return;
2106 * It is OK to access the value here this way since we know
2107 * it exists, we just created it above.
2109 * At NO other time should you access a value in a map or a
2110 * hash_map this way.
2112 clientlist[tempnick] = new userrec();
2114 NonBlocking(socket);
2115 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2117 clientlist[tempnick]->fd = socket;
2118 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2119 strncpy(clientlist[tempnick]->host, host,160);
2120 strncpy(clientlist[tempnick]->dhost, host,160);
2121 strncpy(clientlist[tempnick]->server, ServerName,256);
2122 strncpy(clientlist[tempnick]->ident, "unknown",9);
2123 clientlist[tempnick]->registered = 0;
2124 clientlist[tempnick]->signon = time(NULL);
2125 clientlist[tempnick]->nping = time(NULL)+240;
2126 clientlist[tempnick]->lastping = 1;
2127 clientlist[tempnick]->port = port;
2128 strncpy(clientlist[tempnick]->ip,ip,32);
2132 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2136 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2139 // set the registration timeout for this user
2140 unsigned long class_regtimeout = 90;
2141 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2143 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2145 class_regtimeout = (unsigned long)i->registration_timeout;
2150 int class_flood = 0;
2151 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2153 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2155 class_flood = i->flood;
2160 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2161 clientlist[tempnick]->flood = class_flood;
2163 for (int i = 0; i < MAXCHANS; i++)
2165 clientlist[tempnick]->chans[i].channel = NULL;
2166 clientlist[tempnick]->chans[i].uc_modes = 0;
2169 if (clientlist.size() == MAXCLIENTS)
2170 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2172 char* r = matches_zline(ip);
2175 char reason[MAXBUF];
2176 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2177 kill_link(clientlist[tempnick],reason);
2184 return clientlist.size();
2188 int usercount_invisible(void)
2192 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2194 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2199 int usercount_opers(void)
2203 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2205 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2210 int usercount_unknown(void)
2214 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2216 if ((i->second->fd) && (i->second->registered != 7))
2222 long chancount(void)
2224 return chanlist.size();
2227 long count_servs(void)
2230 //for (int j = 0; j < 255; j++)
2232 // if (servers[j] != NULL)
2238 long servercount(void)
2240 return count_servs()+1;
2246 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2248 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2254 void ShowMOTD(userrec *user)
2258 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2261 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2262 for (int i = 0; i != MOTD.size(); i++)
2264 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2266 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2269 void ShowRULES(userrec *user)
2273 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2276 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2277 for (int i = 0; i != RULES.size(); i++)
2279 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2281 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2284 /* shows the message of the day, and any other on-logon stuff */
2285 void ConnectUser(userrec *user)
2287 user->registered = 7;
2288 user->idle_lastmsg = time(NULL);
2289 log(DEBUG,"ConnectUser: %s",user->nick);
2291 if (strcmp(Passwd(user),"") && (!user->haspassed))
2293 kill_link(user,"Invalid password");
2298 kill_link(user,"Unauthorised connection");
2302 char match_against[MAXBUF];
2303 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2304 char* r = matches_gline(match_against);
2307 char reason[MAXBUF];
2308 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2309 kill_link_silent(user,reason);
2313 r = matches_kline(user->host);
2316 char reason[MAXBUF];
2317 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2318 kill_link_silent(user,reason);
2322 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2323 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2324 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2325 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2326 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2327 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);
2328 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);
2330 FOREACH_MOD OnUserConnect(user);
2331 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2333 char buffer[MAXBUF];
2334 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);
2335 NetSendToAll(buffer);
2338 void handle_version(char **parameters, int pcnt, userrec *user)
2340 char Revision[] = "$Revision$";
2342 char *s1 = Revision;
2344 char *v1 = strtok_r(s1," ",&savept);
2346 char *v2 = strtok_r(s1," ",&savept);
2349 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2353 // calls a handler function for a command
2355 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2357 for (int i = 0; i < cmdlist.size(); i++)
2359 if (!strcasecmp(cmdlist[i].command,commandname))
2361 if (cmdlist[i].handler_function)
2363 if (pcnt>=cmdlist[i].min_params)
2365 if (strchr(user->modes,cmdlist[i].flags_needed))
2367 cmdlist[i].handler_function(parameters,pcnt,user);
2375 void DoSplitEveryone()
2377 bool go_again = true;
2381 for (int i = 0; i < 32; i++)
2385 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2387 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2390 j->CloseConnection();
2391 me[i]->connectors.erase(j);
2399 log(DEBUG,"Removed server. Will remove clients...");
2400 // iterate through the userlist and remove all users on this server.
2401 // because we're dealing with a mesh, we dont have to deal with anything
2402 // "down-route" from this server (nice huh)
2404 char reason[MAXBUF];
2408 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2410 if (strcasecmp(u->second->server,ServerName))
2412 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2413 kill_link(u->second,reason);
2423 char islast(const char* s)
2426 for (int j = 0; j < 32; j++)
2430 for (int k = 0; k < me[j]->connectors.size(); k++)
2432 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2436 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2446 long map_count(const char* s)
2449 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2451 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2457 void force_nickchange(userrec* user,const char* newnick)
2464 FOREACH_RESULT(OnUserPreNick(user,newnick));
2466 kill_link(user,"Nickname collision");
2469 if (matches_qline(newnick))
2471 kill_link(user,"Nickname collision");
2479 strncpy(nick,newnick,MAXBUF);
2481 if (user->registered == 7)
2485 handle_nick(pars,1,user);
2491 int process_parameters(char **command_p,char *parameters)
2496 q = strlen(parameters);
2499 /* no parameters, command_p invalid! */
2502 if (parameters[0] == ':')
2504 command_p[0] = parameters+1;
2509 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2511 /* only one parameter */
2512 command_p[0] = parameters;
2513 if (parameters[0] == ':')
2515 if (strchr(parameters,' ') != NULL)
2523 command_p[j++] = parameters;
2524 for (int i = 0; i <= q; i++)
2526 if (parameters[i] == ' ')
2528 command_p[j++] = parameters+i+1;
2529 parameters[i] = '\0';
2530 if (command_p[j-1][0] == ':')
2532 *command_p[j-1]++; /* remove dodgy ":" */
2534 /* parameter like this marks end of the sequence */
2538 return j; /* returns total number of items in the list */
2541 void process_command(userrec *user, char* cmd)
2545 char *command_p[127];
2546 char p[MAXBUF], temp[MAXBUF];
2547 int i, j, items, cmd_found;
2549 for (int i = 0; i < 127; i++)
2550 command_p[i] = NULL;
2560 if (!strcmp(cmd,""))
2565 int total_params = 0;
2568 for (int q = 0; q < strlen(cmd)-1; q++)
2570 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2573 // found a 'trailing', we dont count them after this.
2581 // another phidjit bug...
2582 if (total_params > 126)
2584 kill_link(user,"Protocol violation (1)");
2590 std::string tmp = cmd;
2591 for (int i = 0; i <= MODCOUNT; i++)
2593 std::string oldtmp = tmp;
2594 modules[i]->OnServerRaw(tmp,true);
2597 log(DEBUG,"A Module changed the input string!");
2598 log(DEBUG,"New string: %s",tmp.c_str());
2599 log(DEBUG,"Old string: %s",oldtmp.c_str());
2603 strncpy(cmd,tmp.c_str(),MAXBUF);
2606 if (!strchr(cmd,' '))
2608 /* no parameters, lets skip the formalities and not chop up
2610 log(DEBUG,"About to preprocess command with no params");
2612 command_p[0] = NULL;
2614 for (int i = 0; i <= strlen(cmd); i++)
2616 cmd[i] = toupper(cmd[i]);
2618 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2625 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2626 for (int i = 0; i < strlen(temp); i++)
2628 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2634 /* split the full string into a command plus parameters */
2638 if (strchr(cmd,' '))
2640 for (int i = 0; i <= strlen(cmd); i++)
2642 /* capitalise the command ONLY, leave params intact */
2643 cmd[i] = toupper(cmd[i]);
2644 /* are we nearly there yet?! :P */
2648 parameters = cmd+i+1;
2656 for (int i = 0; i <= strlen(cmd); i++)
2658 cmd[i] = toupper(cmd[i]);
2665 if (strlen(command)>MAXCOMMAND)
2667 kill_link(user,"Protocol violation (2)");
2671 for (int x = 0; x < strlen(command); x++)
2673 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2675 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2677 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2679 kill_link(user,"Protocol violation (3)");
2686 for (int i = 0; i != cmdlist.size(); i++)
2688 if (strcmp(cmdlist[i].command,""))
2690 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2692 log(DEBUG,"Found matching command");
2696 if (strcmp(parameters,""))
2698 items = process_parameters(command_p,parameters);
2703 command_p[0] = NULL;
2709 command_p[0] = NULL;
2714 log(DEBUG,"Processing command");
2716 /* activity resets the ping pending timer */
2717 user->nping = time(NULL) + 120;
2718 if ((items) < cmdlist[i].min_params)
2720 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2721 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2724 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2726 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2727 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2731 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2733 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2735 if ((!isnick(user->nick)) || (user->registered != 7))
2737 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2738 WriteServ(user->fd,"451 %s :You have not registered",command);
2742 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2744 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2745 if (cmdlist[i].handler_function)
2747 /* ikky /stats counters */
2752 user->bytes_in += strlen(temp);
2755 cmdlist[i].use_count++;
2756 cmdlist[i].total_bytes+=strlen(temp);
2759 /* WARNING: nothing may come after the
2760 * command handler call, as the handler
2761 * may free the user structure! */
2763 cmdlist[i].handler_function(command_p,items,user);
2769 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2770 WriteServ(user->fd,"451 %s :You have not registered",command);
2778 if ((!cmd_found) && (user))
2780 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2781 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2786 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2789 /* create the command and push it onto the table */
2790 strcpy(comm.command,cmd);
2791 comm.handler_function = f;
2792 comm.flags_needed = flags;
2793 comm.min_params = minparams;
2795 comm.total_bytes = 0;
2796 cmdlist.push_back(comm);
2797 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2800 void SetupCommandTable(void)
2802 createcommand("USER",handle_user,0,4);
2803 createcommand("NICK",handle_nick,0,1);
2804 createcommand("QUIT",handle_quit,0,0);
2805 createcommand("VERSION",handle_version,0,0);
2806 createcommand("PING",handle_ping,0,1);
2807 createcommand("PONG",handle_pong,0,1);
2808 createcommand("ADMIN",handle_admin,0,0);
2809 createcommand("PRIVMSG",handle_privmsg,0,2);
2810 createcommand("INFO",handle_info,0,0);
2811 createcommand("TIME",handle_time,0,0);
2812 createcommand("WHOIS",handle_whois,0,1);
2813 createcommand("WALLOPS",handle_wallops,'o',1);
2814 createcommand("NOTICE",handle_notice,0,2);
2815 createcommand("JOIN",handle_join,0,1);
2816 createcommand("NAMES",handle_names,0,1);
2817 createcommand("PART",handle_part,0,1);
2818 createcommand("KICK",handle_kick,0,2);
2819 createcommand("MODE",handle_mode,0,1);
2820 createcommand("TOPIC",handle_topic,0,1);
2821 createcommand("WHO",handle_who,0,1);
2822 createcommand("MOTD",handle_motd,0,0);
2823 createcommand("RULES",handle_rules,0,0);
2824 createcommand("OPER",handle_oper,0,2);
2825 createcommand("LIST",handle_list,0,0);
2826 createcommand("DIE",handle_die,'o',1);
2827 createcommand("RESTART",handle_restart,'o',1);
2828 createcommand("KILL",handle_kill,'o',2);
2829 createcommand("REHASH",handle_rehash,'o',0);
2830 createcommand("LUSERS",handle_lusers,0,0);
2831 createcommand("STATS",handle_stats,0,1);
2832 createcommand("USERHOST",handle_userhost,0,1);
2833 createcommand("AWAY",handle_away,0,0);
2834 createcommand("ISON",handle_ison,0,0);
2835 createcommand("SUMMON",handle_summon,0,0);
2836 createcommand("USERS",handle_users,0,0);
2837 createcommand("INVITE",handle_invite,0,2);
2838 createcommand("PASS",handle_pass,0,1);
2839 createcommand("TRACE",handle_trace,'o',0);
2840 createcommand("WHOWAS",handle_whowas,0,1);
2841 createcommand("CONNECT",handle_connect,'o',1);
2842 createcommand("SQUIT",handle_squit,'o',0);
2843 createcommand("MODULES",handle_modules,'o',0);
2844 createcommand("LINKS",handle_links,0,0);
2845 createcommand("MAP",handle_map,0,0);
2846 createcommand("KLINE",handle_kline,'o',1);
2847 createcommand("GLINE",handle_gline,'o',1);
2848 createcommand("ZLINE",handle_zline,'o',1);
2849 createcommand("QLINE",handle_qline,'o',1);
2852 void process_buffer(const char* cmdbuf,userrec *user)
2856 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2863 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2866 if (!strcmp(cmdbuf,""))
2870 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2872 strncpy(cmd,cmdbuf,MAXBUF);
2873 if (!strcmp(cmd,""))
2877 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2879 cmd[strlen(cmd)-1] = '\0';
2881 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2883 cmd[strlen(cmd)-1] = '\0';
2886 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2888 cmd[strlen(cmd)-1] = '\0';
2891 if (!strcmp(cmd,""))
2895 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2897 if ((user) && (cmd))
2899 process_command(user,cmd);
2903 void DoSync(serverrec* serv, char* tcp_host)
2906 log(DEBUG,"Sending sync");
2907 // send start of sync marker: Y <timestamp>
2908 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2909 // except the ones its receiving it from.
2910 snprintf(data,MAXBUF,"Y %d",time(NULL));
2911 serv->SendPacket(data,tcp_host);
2912 // send users and channels
2913 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2915 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);
2916 serv->SendPacket(data,tcp_host);
2917 if (strcmp(chlist(u->second),""))
2919 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2920 serv->SendPacket(data,tcp_host);
2923 // send channel modes, topics etc...
2924 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2926 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2927 serv->SendPacket(data,tcp_host);
2928 if (strcmp(c->second->topic,""))
2930 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2931 serv->SendPacket(data,tcp_host);
2933 // send current banlist
2935 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2937 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2938 serv->SendPacket(data,tcp_host);
2941 // sync global zlines, glines, etc
2942 sync_xlines(serv,tcp_host);
2943 snprintf(data,MAXBUF,"F %d",time(NULL));
2944 serv->SendPacket(data,tcp_host);
2945 log(DEBUG,"Sent sync");
2946 // ircd sends its serverlist after the end of sync here
2950 void NetSendMyRoutingTable()
2952 // send out a line saying what is reachable to us.
2953 // E.g. if A is linked to B C and D, send out:
2955 // if its only linked to B and D send out:
2957 // if it has no links, dont even send out the line at all.
2958 char buffer[MAXBUF];
2959 sprintf(buffer,"$ %s",ServerName);
2960 bool sendit = false;
2961 for (int i = 0; i < 32; i++)
2965 for (int j = 0; j < me[i]->connectors.size(); j++)
2967 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2969 strncat(buffer," ",MAXBUF);
2970 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2977 NetSendToAll(buffer);
2981 void DoSplit(const char* params)
2983 bool go_again = true;
2987 for (int i = 0; i < 32; i++)
2991 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2993 if (!strcasecmp(j->GetServerName().c_str(),params))
2996 j->CloseConnection();
2997 me[i]->connectors.erase(j);
3005 log(DEBUG,"Removed server. Will remove clients...");
3006 // iterate through the userlist and remove all users on this server.
3007 // because we're dealing with a mesh, we dont have to deal with anything
3008 // "down-route" from this server (nice huh)
3010 char reason[MAXBUF];
3011 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3015 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3017 if (!strcasecmp(u->second->server,params))
3019 kill_link(u->second,reason);
3027 // removes a server. Will NOT remove its users!
3029 void RemoveServer(const char* name)
3031 bool go_again = true;
3035 for (int i = 0; i < 32; i++)
3039 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3041 if (!strcasecmp(j->GetServerName().c_str(),name))
3044 j->CloseConnection();
3045 me[i]->connectors.erase(j);
3056 int reap_counter = 0;
3060 struct sockaddr_in client, server;
3061 char addrs[MAXBUF][255];
3062 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3064 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3065 int selectResult = 0, selectResult2 = 0;
3066 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3067 char resolvedHost[MAXBUF];
3071 log_file = fopen("ircd.log","a+");
3074 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3078 log(DEBUG,"InspIRCd: startup: begin");
3082 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3084 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3086 SetupCommandTable();
3087 log(DEBUG,"InspIRCd: startup: default command table set up");
3090 if (strcmp(DieValue,""))
3092 printf("WARNING: %s\n\n",DieValue);
3095 log(DEBUG,"InspIRCd: startup: read config");
3097 int count2 = 0, count3 = 0;
3099 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3101 ConfValue("bind","port",count,configToken,&config_f);
3102 ConfValue("bind","address",count,Addr,&config_f);
3103 ConfValue("bind","type",count,Type,&config_f);
3104 if (!strcmp(Type,"servers"))
3106 char Default[MAXBUF];
3107 strcpy(Default,"no");
3108 ConfValue("bind","default",count,Default,&config_f);
3109 if (strchr(Default,'y'))
3111 defaultRoute = count3;
3112 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3114 me[count3] = new serverrec(ServerName,100L,false);
3115 me[count3]->CreateListener(Addr,atoi(configToken));
3120 ports[count2] = atoi(configToken);
3121 strcpy(addrs[count2],Addr);
3124 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3127 UDPportCount = count3;
3129 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3131 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3135 /* BugFix By Craig! :p */
3137 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3139 char modfile[MAXBUF];
3140 ConfValue("module","name",count2,configToken,&config_f);
3141 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3142 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3143 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3144 /* If The File Doesnt exist, Trying to load it
3145 * Will Segfault the IRCd.. So, check to see if
3146 * it Exists, Before Proceeding. */
3147 if (FileExists(modfile))
3149 factory[count] = new ircd_module(modfile);
3150 if (factory[count]->LastError())
3152 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3153 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3156 if (factory[count]->factory)
3158 modules[count] = factory[count]->factory->CreateModule();
3159 /* save the module and the module's classfactory, if
3160 * this isnt done, random crashes can occur :/ */
3161 module_names.push_back(modfile);
3165 log(DEBUG,"Unable to load %s",modfile);
3166 sprintf("Unable to load %s\nExiting...\n",modfile);
3169 /* Increase the Count */
3174 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3175 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3178 MODCOUNT = count - 1;
3179 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3181 printf("\nInspIRCd is now running!\n");
3183 startup_time = time(NULL);
3187 log(VERBOSE,"Not forking as -nofork was specified");
3191 if (DaemonSeed() == ERROR)
3193 log(DEBUG,"InspIRCd: startup: can't daemonise");
3194 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3200 /* setup select call */
3201 FD_ZERO(&selectFds);
3202 log(DEBUG,"InspIRCd: startup: zero selects");
3203 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3205 for (count = 0; count < portCount; count++)
3207 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3209 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3212 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3214 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3216 else /* well we at least bound to one socket so we'll continue */
3222 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3224 /* if we didn't bind to anything then abort */
3225 if (boundPortCount == 0)
3227 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3232 length = sizeof (client);
3233 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3235 /* main loop, this never returns */
3238 #ifdef _POSIX_PRIORITY_SCHEDULING
3241 // update the status of klines, etc
3248 user_hash::iterator count2 = clientlist.begin();
3250 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3251 // them in a list, then reap the list every second or so.
3252 if (reap_counter>300)
3254 if (fd_reap.size() > 0)
3256 for( int n = 0; n < fd_reap.size(); n++)
3258 Blocking(fd_reap[n]);
3260 NonBlocking(fd_reap[n]);
3269 FD_ZERO(&serverfds);
3272 for (int x = 0; x != UDPportCount; x++)
3274 FD_SET(me[x]->fd, &serverfds);
3280 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3283 for (int x = 0; x != UDPportCount; x++)
3285 if (FD_ISSET (me[x]->fd, &serverfds))
3287 char remotehost[MAXBUF],resolved[MAXBUF];
3288 length = sizeof (client);
3289 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3290 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3291 if(CleanAndResolve(resolved, remotehost) != TRUE)
3293 strncpy(resolved,remotehost,MAXBUF);
3295 // add to this connections ircd_connector vector
3296 // *FIX* - we need the LOCAL port not the remote port in &client!
3297 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3302 for (int x = 0; x < UDPportCount; x++)
3304 std::deque<std::string> msgs;
3306 if (me[x]->RecvPacket(msgs, tcp_host))
3308 for (int ctr = 0; ctr < msgs.size(); ctr++)
3310 char udp_msg[MAXBUF];
3311 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3312 if (strlen(udp_msg)<1)
3314 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3317 // during a netburst, send all data to all other linked servers
3318 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3320 if (is_uline(tcp_host))
3322 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3324 NetSendToAllExcept(tcp_host,udp_msg);
3328 NetSendToAllExcept(tcp_host,udp_msg);
3330 FOREACH_MOD OnPacketReceive(udp_msg);
3331 handle_link_packet(udp_msg, tcp_host, me[x]);
3338 while (count2 != clientlist.end())
3341 tval.tv_usec = tval.tv_sec = 0;
3343 int total_in_this_set = 0;
3345 user_hash::iterator xcount = count2;
3346 user_hash::iterator endingiter = count2;
3348 if (!count2->second) break;
3351 if (count2->second->fd != 0)
3353 // assemble up to 64 sockets into an fd_set
3354 // to implement a pooling mechanism.
3356 // This should be up to 64x faster than the
3357 // old implementation.
3358 while (total_in_this_set < 64)
3360 if (count2 != clientlist.end())
3362 // we don't check the state of remote users.
3363 if (count2->second->fd > 0)
3365 FD_SET (count2->second->fd, &sfd);
3367 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3368 // their connection class.
3369 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3371 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3372 kill_link(count2->second,"Registration timeout");
3375 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3377 if ((!count2->second->lastping) && (count2->second->registered == 7))
3379 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3380 kill_link(count2->second,"Ping timeout");
3383 Write(count2->second->fd,"PING :%s",ServerName);
3384 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3385 count2->second->lastping = 0;
3386 count2->second->nping = time(NULL)+120;
3390 total_in_this_set++;
3395 endingiter = count2;
3396 count2 = xcount; // roll back to where we were
3402 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3404 // now loop through all of the items in this pool if any are waiting
3405 //if (selectResult2 > 0)
3406 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3409 #ifdef _POSIX_PRIORITY_SCHEDULING
3414 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3416 log(DEBUG,"Reading fd %d",count2a->second->fd);
3417 memset(data, 0, 10240);
3418 result = read(count2a->second->fd, data, 10240);
3423 log(DEBUG,"Read %d characters from socket",result);
3424 userrec* current = count2a->second;
3425 int currfd = current->fd;
3426 char* l = strtok(data,"\n");
3431 if ((floodlines > current->flood) && (current->flood != 0))
3433 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3434 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3435 kill_link(current,"Excess flood");
3438 char sanitized[NetBufferSize];
3439 memset(sanitized, 0, NetBufferSize);
3441 for (int pt = 0; pt < strlen(l); pt++)
3445 sanitized[ptt++] = l[pt];
3448 sanitized[ptt] = '\0';
3449 if (strlen(sanitized))
3453 // we're gonna re-scan to check if the nick is gone, after every
3454 // command - if it has, we're gonna bail
3455 bool find_again = false;
3456 process_buffer(sanitized,current);
3458 // look for the user's record in case it's changed
3459 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3461 if (c2->second->fd == currfd)
3463 // found again, update pointer
3464 current == c2->second;
3473 l = strtok(NULL,"\n");
3478 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3480 log(DEBUG,"killing: %s",count2a->second->nick);
3481 kill_link(count2a->second,strerror(errno));
3485 // result EAGAIN means nothing read
3486 if (result == EAGAIN)
3494 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3495 kill_link(count2a->second,"Client exited");
3496 // must bail here? kill_link removes the hash, corrupting the iterator
3497 log(DEBUG,"Bailing from client exit");
3501 else if (result > 0)
3506 for (int q = 0; q < total_in_this_set; q++)
3508 // there is no iterator += operator :(
3509 //if (count2 != clientlist.end())
3516 // set up select call
3517 for (count = 0; count < boundPortCount; count++)
3519 FD_SET (openSockfd[count], &selectFds);
3523 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3525 /* select is reporting a waiting socket. Poll them all to find out which */
3526 if (selectResult > 0)
3528 char target[MAXBUF], resolved[MAXBUF];
3529 for (count = 0; count < boundPortCount; count++)
3531 if (FD_ISSET (openSockfd[count], &selectFds))
3533 length = sizeof (client);
3534 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3536 address_cache::iterator iter = IP.find(client.sin_addr);
3537 bool iscached = false;
3538 if (iter == IP.end())
3540 /* ip isn't in cache, add it */
3541 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3542 if(CleanAndResolve(resolved, target) != TRUE)
3544 strncpy(resolved,target,MAXBUF);
3546 /* hostname now in 'target' */
3547 IP[client.sin_addr] = new string(resolved);
3548 /* hostname in cache */
3552 /* found ip (cached) */
3553 strncpy(resolved, iter->second->c_str(), MAXBUF);
3557 if (incomingSockfd < 0)
3559 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3560 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3564 AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3565 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3572 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3575 close (incomingSockfd);