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,chan->key,MAXBUF);
1130 sprintf(foo," %d",chan->limit);
1131 strncat(sparam,foo,MAXBUF);
1133 if (strlen(chan->custom_modes))
1135 strncat(scratch,chan->custom_modes,MAXMODES);
1136 for (int z = 0; z < strlen(chan->custom_modes); z++)
1138 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1141 strncat(sparam," ",MAXBUF);
1142 strncat(sparam,extparam.c_str(),MAXBUF);
1146 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1147 strncat(scratch,sparam,MAXMODES);
1152 /* compile a userlist of a channel into a string, each nick seperated by
1153 * spaces and op, voice etc status shown as @ and + */
1155 void userlist(userrec *user,chanrec *c)
1157 if ((!c) || (!user))
1159 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1163 sprintf(list,"353 %s = %s :", user->nick, c->name);
1164 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1166 if (has_channel(i->second,c))
1168 if (isnick(i->second->nick))
1170 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1172 /* user is +i, and source not on the channel, does not show
1173 * nick in NAMES list */
1176 strcat(list,cmode(i->second,c));
1177 strcat(list,i->second->nick);
1179 if (strlen(list)>(480-NICKMAX))
1181 /* list overflowed into
1182 * multiple numerics */
1183 WriteServ(user->fd,list);
1184 sprintf(list,"353 %s = %s :", user->nick, c->name);
1189 /* if whats left in the list isnt empty, send it */
1190 if (list[strlen(list)-1] != ':')
1192 WriteServ(user->fd,list);
1196 /* return a count of the users on a specific channel accounting for
1197 * invisible users who won't increase the count. e.g. for /LIST */
1199 int usercount_i(chanrec *c)
1206 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1211 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1215 if (has_channel(i->second,c))
1217 if (isnick(i->second->nick))
1219 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1221 /* user is +i, and source not on the channel, does not show
1222 * nick in NAMES list */
1230 log(DEBUG,"usercount_i: %s %d",c->name,count);
1235 int usercount(chanrec *c)
1242 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1247 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1251 if (has_channel(i->second,c))
1253 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1260 log(DEBUG,"usercount: %s %d",c->name,count);
1265 /* add a channel to a user, creating the record for it if needed and linking
1266 * it to the user record */
1268 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1270 if ((!user) || (!cn))
1272 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1281 strncpy(cname,cn,MAXBUF);
1283 // we MUST declare this wherever we use FOREACH_RESULT
1286 if (strlen(cname) > CHANMAX-1)
1288 cname[CHANMAX-1] = '\0';
1291 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1293 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1295 return NULL; // already on the channel!
1299 if (!FindChan(cname))
1301 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1306 /* create a new one */
1307 log(DEBUG,"add_channel: creating: %s",cname);
1309 chanlist[cname] = new chanrec();
1311 strcpy(chanlist[cname]->name, cname);
1312 chanlist[cname]->topiclock = 1;
1313 chanlist[cname]->noexternal = 1;
1314 chanlist[cname]->created = time(NULL);
1315 strcpy(chanlist[cname]->topic, "");
1316 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1317 chanlist[cname]->topicset = 0;
1318 Ptr = chanlist[cname];
1319 log(DEBUG,"add_channel: created: %s",cname);
1320 /* set created to 2 to indicate user
1321 * is the first in the channel
1322 * and should be given ops */
1328 /* channel exists, just fish out a pointer to its struct */
1329 Ptr = FindChan(cname);
1332 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1334 // the override flag allows us to bypass channel modes
1335 // and bans (used by servers)
1338 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1343 if (strcmp(Ptr->key,""))
1345 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1348 log(DEBUG,"add_channel: no key given in JOIN");
1349 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1354 log(DEBUG,"key at %p is %s",key,key);
1355 if (strcasecmp(key,Ptr->key))
1357 log(DEBUG,"add_channel: bad key given in JOIN");
1358 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1363 log(DEBUG,"add_channel: no key");
1365 if (Ptr->inviteonly)
1367 log(DEBUG,"add_channel: channel is +i");
1368 if (user->IsInvited(Ptr->name))
1370 /* user was invited to channel */
1371 /* there may be an optional channel NOTICE here */
1375 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1379 log(DEBUG,"add_channel: channel is not +i");
1383 if (usercount(Ptr) == Ptr->limit)
1385 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1390 log(DEBUG,"add_channel: about to walk banlist");
1392 /* check user against the channel banlist */
1395 if (Ptr->bans.size())
1397 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1399 if (match(user->GetFullHost(),i->data))
1401 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1408 log(DEBUG,"add_channel: bans checked");
1411 if ((Ptr) && (user))
1413 user->RemoveInvite(Ptr->name);
1416 log(DEBUG,"add_channel: invites removed");
1421 log(DEBUG,"Overridden checks");
1429 log(DEBUG,"Passed channel checks");
1431 for (int i =0; i != MAXCHANS; i++)
1433 log(DEBUG,"Check location %d",i);
1434 if (user->chans[i].channel == NULL)
1436 log(DEBUG,"Adding into their channel list at location %d",i);
1440 /* first user in is given ops */
1441 user->chans[i].uc_modes = UCMODE_OP;
1445 user->chans[i].uc_modes = 0;
1447 user->chans[i].channel = Ptr;
1448 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1450 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1452 // use the stamdard J token with no privilages.
1453 char buffer[MAXBUF];
1454 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1455 NetSendToAll(buffer);
1458 log(DEBUG,"Sent JOIN to client");
1462 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1463 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1466 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1467 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1468 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1469 FOREACH_MOD OnUserJoin(user,Ptr);
1473 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1474 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1478 /* remove a channel from a users record, and remove the record from memory
1479 * if the channel has become empty */
1481 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1483 if ((!user) || (!cname))
1485 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1492 if ((!cname) || (!user))
1497 Ptr = FindChan(cname);
1504 FOREACH_MOD OnUserPart(user,Ptr);
1505 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1507 for (int i =0; i != MAXCHANS; i++)
1509 /* zap it from the channel list of the user */
1510 if (user->chans[i].channel == Ptr)
1514 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1518 char buffer[MAXBUF];
1519 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1520 NetSendToAll(buffer);
1529 char buffer[MAXBUF];
1530 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1531 NetSendToAll(buffer);
1534 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1536 user->chans[i].uc_modes = 0;
1537 user->chans[i].channel = NULL;
1538 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1543 /* if there are no users left on the channel */
1544 if (!usercount(Ptr))
1546 chan_hash::iterator iter = chanlist.find(Ptr->name);
1548 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1550 /* kill the record */
1551 if (iter != chanlist.end())
1553 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1554 delete iter->second;
1555 chanlist.erase(iter);
1561 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1563 if ((!src) || (!user) || (!Ptr) || (!reason))
1565 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1572 if ((!Ptr) || (!user) || (!src))
1577 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1579 if (!has_channel(user,Ptr))
1581 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1584 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1586 if (cstatus(src,Ptr) == STATUS_HOP)
1588 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1592 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1598 for (int i =0; i != MAXCHANS; i++)
1600 /* zap it from the channel list of the user */
1601 if (user->chans[i].channel)
1602 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1604 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1605 user->chans[i].uc_modes = 0;
1606 user->chans[i].channel = NULL;
1607 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1612 /* if there are no users left on the channel */
1613 if (!usercount(Ptr))
1615 chan_hash::iterator iter = chanlist.find(Ptr->name);
1617 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1619 /* kill the record */
1620 if (iter != chanlist.end())
1622 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1623 delete iter->second;
1624 chanlist.erase(iter);
1632 /* This function pokes and hacks at a parameter list like the following:
1634 * PART #winbot, #darkgalaxy :m00!
1636 * to turn it into a series of individual calls like this:
1638 * PART #winbot :m00!
1639 * PART #darkgalaxy :m00!
1641 * The seperate calls are sent to a callback function provided by the caller
1642 * (the caller will usually call itself recursively). The callback function
1643 * must be a command handler. Calling this function on a line with no list causes
1644 * no action to be taken. You must provide a starting and ending parameter number
1645 * where the range of the list can be found, useful if you have a terminating
1646 * parameter as above which is actually not part of the list, or parameters
1647 * before the actual list as well. This code is used by many functions which
1648 * can function as "one to list" (see the RFC) */
1650 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1655 char blog[32][MAXBUF];
1656 char blog2[32][MAXBUF];
1657 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1658 char keystr[MAXBUF];
1661 for (int i = 0; i <32; i++)
1664 for (int i = 0; i <32; i++)
1665 strcpy(blog2[i],"");
1668 for (int i = 0; i <10; i++)
1672 parameters[i] = moo;
1677 if (pcnt > 1) /* we have a key to copy */
1679 strcpy(keystr,parameters[1]);
1683 if (!parameters[start])
1687 if (!strchr(parameters[start],','))
1692 for (int i = start; i <= end; i++)
1696 strcat(plist,parameters[i]);
1704 for (int i = 0; i < t; i++)
1706 if (plist[i] == ',')
1709 strcpy(blog[j++],param);
1713 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1718 strcpy(blog[j++],param);
1721 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1726 if ((joins) && (keystr))
1728 if (strchr(keystr,','))
1732 t2 = strlen(keystr);
1733 for (int i = 0; i < t2; i++)
1735 if (keystr[i] == ',')
1738 strcpy(blog2[j++],param);
1742 strcpy(blog2[j++],param);
1747 for (j = 0; j < total; j++)
1753 for (q = end; q < pcnt-1; q++)
1755 if (parameters[q+1])
1757 pars[q-end+1] = parameters[q+1];
1760 if ((joins) && (parameters[1]))
1771 /* repeatedly call the function with the hacked parameter list */
1772 if ((joins) && (pcnt > 1))
1776 // pars[1] already set up and containing key from blog2[j]
1781 pars[1] = parameters[1];
1787 fn(pars,pcnt-(end-start),u);
1796 void kill_link(userrec *user,const char* r)
1798 user_hash::iterator iter = clientlist.find(user->nick);
1800 char reason[MAXBUF];
1802 strncpy(reason,r,MAXBUF);
1804 if (strlen(reason)>MAXQUIT)
1806 reason[MAXQUIT-1] = '\0';
1809 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1810 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1811 log(DEBUG,"closing fd %d",user->fd);
1813 /* bugfix, cant close() a nonblocking socket (sux!) */
1814 if (user->registered == 7) {
1815 FOREACH_MOD OnUserQuit(user);
1816 WriteCommonExcept(user,"QUIT :%s",reason);
1818 // Q token must go to ALL servers!!!
1819 char buffer[MAXBUF];
1820 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1821 NetSendToAll(buffer);
1824 /* push the socket on a stack of sockets due to be closed at the next opportunity
1825 * 'Client exited' is an exception to this as it means the client side has already
1826 * closed the socket, we don't need to do it.
1828 fd_reap.push_back(user->fd);
1830 bool do_purge = false;
1832 if (user->registered == 7) {
1833 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1837 if (iter != clientlist.end())
1839 log(DEBUG,"deleting user hash value %d",iter->second);
1840 if ((iter->second) && (user->registered == 7)) {
1841 delete iter->second;
1843 clientlist.erase(iter);
1846 if (user->registered == 7) {
1847 purge_empty_chans();
1851 void kill_link_silent(userrec *user,const char* r)
1853 user_hash::iterator iter = clientlist.find(user->nick);
1855 char reason[MAXBUF];
1857 strncpy(reason,r,MAXBUF);
1859 if (strlen(reason)>MAXQUIT)
1861 reason[MAXQUIT-1] = '\0';
1864 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1865 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1866 log(DEBUG,"closing fd %d",user->fd);
1868 /* bugfix, cant close() a nonblocking socket (sux!) */
1869 if (user->registered == 7) {
1870 FOREACH_MOD OnUserQuit(user);
1871 WriteCommonExcept(user,"QUIT :%s",reason);
1873 // Q token must go to ALL servers!!!
1874 char buffer[MAXBUF];
1875 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1876 NetSendToAll(buffer);
1879 /* push the socket on a stack of sockets due to be closed at the next opportunity
1880 * 'Client exited' is an exception to this as it means the client side has already
1881 * closed the socket, we don't need to do it.
1883 fd_reap.push_back(user->fd);
1885 bool do_purge = false;
1887 if (iter != clientlist.end())
1889 log(DEBUG,"deleting user hash value %d",iter->second);
1890 if ((iter->second) && (user->registered == 7)) {
1891 delete iter->second;
1893 clientlist.erase(iter);
1896 if (user->registered == 7) {
1897 purge_empty_chans();
1903 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1905 char* Passwd(userrec *user)
1907 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1909 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1917 bool IsDenied(userrec *user)
1919 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1921 if (match(user->host,i->host) && (i->type == CC_DENY))
1932 /* sends out an error notice to all connected clients (not to be used
1935 void send_error(char *s)
1937 log(DEBUG,"send_error: %s",s);
1938 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1940 if (isnick(i->second->nick))
1942 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1946 // fix - unregistered connections receive ERROR, not NOTICE
1947 Write(i->second->fd,"ERROR :%s",s);
1952 void Error(int status)
1954 signal (SIGALRM, SIG_IGN);
1955 signal (SIGPIPE, SIG_IGN);
1956 signal (SIGTERM, SIG_IGN);
1957 signal (SIGABRT, SIG_IGN);
1958 signal (SIGSEGV, SIG_IGN);
1959 signal (SIGURG, SIG_IGN);
1960 signal (SIGKILL, SIG_IGN);
1961 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1962 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1967 int main(int argc, char *argv[])
1971 log(DEBUG,"*** InspIRCd starting up!");
1972 if (!FileExists(CONFIG_FILE))
1974 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1975 log(DEBUG,"main: no config");
1976 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1980 if (!strcmp(argv[1],"-nofork")) {
1984 if (InspIRCd() == ERROR)
1986 log(DEBUG,"main: daemon function bailed");
1987 printf("ERROR: could not initialise. Shutting down.\n");
1994 template<typename T> inline string ConvToStr(const T &in)
1997 if (!(tmp << in)) return string();
2001 /* re-allocates a nick in the user_hash after they change nicknames,
2002 * returns a pointer to the new user as it may have moved */
2004 userrec* ReHashNick(char* Old, char* New)
2006 user_hash::iterator newnick;
2007 user_hash::iterator oldnick = clientlist.find(Old);
2009 log(DEBUG,"ReHashNick: %s %s",Old,New);
2011 if (!strcasecmp(Old,New))
2013 log(DEBUG,"old nick is new nick, skipping");
2014 return oldnick->second;
2017 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2019 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2021 clientlist[New] = new userrec();
2022 clientlist[New] = oldnick->second;
2023 /*delete oldnick->second; */
2024 clientlist.erase(oldnick);
2026 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2028 return clientlist[New];
2031 /* adds or updates an entry in the whowas list */
2032 void AddWhoWas(userrec* u)
2034 user_hash::iterator iter = whowas.find(u->nick);
2035 userrec *a = new userrec();
2036 strcpy(a->nick,u->nick);
2037 strcpy(a->ident,u->ident);
2038 strcpy(a->dhost,u->dhost);
2039 strcpy(a->host,u->host);
2040 strcpy(a->fullname,u->fullname);
2041 strcpy(a->server,u->server);
2042 a->signon = u->signon;
2044 /* MAX_WHOWAS: max number of /WHOWAS items
2045 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2046 * can be replaced by a newer one
2049 if (iter == whowas.end())
2051 if (whowas.size() == WHOWAS_MAX)
2053 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2055 // 3600 seconds in an hour ;)
2056 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2060 log(DEBUG,"added WHOWAS entry, purged an old record");
2067 log(DEBUG,"added fresh WHOWAS entry");
2068 whowas[a->nick] = a;
2073 log(DEBUG,"updated WHOWAS entry");
2074 delete iter->second;
2080 /* add a client connection to the sockets list */
2081 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2085 char resolved[MAXBUF];
2088 user_hash::iterator iter;
2090 tempnick = ConvToStr(socket) + "-unknown";
2091 sprintf(tn2,"%d-unknown",socket);
2093 iter = clientlist.find(tempnick);
2095 if (iter != clientlist.end()) return;
2098 * It is OK to access the value here this way since we know
2099 * it exists, we just created it above.
2101 * At NO other time should you access a value in a map or a
2102 * hash_map this way.
2104 clientlist[tempnick] = new userrec();
2106 NonBlocking(socket);
2107 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2109 clientlist[tempnick]->fd = socket;
2110 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2111 strncpy(clientlist[tempnick]->host, host,160);
2112 strncpy(clientlist[tempnick]->dhost, host,160);
2113 strncpy(clientlist[tempnick]->server, ServerName,256);
2114 strncpy(clientlist[tempnick]->ident, "unknown",9);
2115 clientlist[tempnick]->registered = 0;
2116 clientlist[tempnick]->signon = time(NULL);
2117 clientlist[tempnick]->nping = time(NULL)+240;
2118 clientlist[tempnick]->lastping = 1;
2119 clientlist[tempnick]->port = port;
2120 strncpy(clientlist[tempnick]->ip,ip,32);
2124 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2128 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2131 // set the registration timeout for this user
2132 unsigned long class_regtimeout = 90;
2133 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2135 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2137 class_regtimeout = (unsigned long)i->registration_timeout;
2142 int class_flood = 0;
2143 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2145 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2147 class_flood = i->flood;
2152 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2153 clientlist[tempnick]->flood = class_flood;
2155 for (int i = 0; i < MAXCHANS; i++)
2157 clientlist[tempnick]->chans[i].channel = NULL;
2158 clientlist[tempnick]->chans[i].uc_modes = 0;
2161 if (clientlist.size() == MAXCLIENTS)
2162 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2164 char* r = matches_zline(ip);
2167 char reason[MAXBUF];
2168 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2169 kill_link(clientlist[tempnick],reason);
2176 return clientlist.size();
2180 int usercount_invisible(void)
2184 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2186 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2191 int usercount_opers(void)
2195 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2197 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2202 int usercount_unknown(void)
2206 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2208 if ((i->second->fd) && (i->second->registered != 7))
2214 long chancount(void)
2216 return chanlist.size();
2219 long count_servs(void)
2222 //for (int j = 0; j < 255; j++)
2224 // if (servers[j] != NULL)
2230 long servercount(void)
2232 return count_servs()+1;
2238 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2240 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2246 void ShowMOTD(userrec *user)
2250 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2253 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2254 for (int i = 0; i != MOTD.size(); i++)
2256 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2258 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2261 void ShowRULES(userrec *user)
2265 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2268 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2269 for (int i = 0; i != RULES.size(); i++)
2271 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2273 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2276 /* shows the message of the day, and any other on-logon stuff */
2277 void ConnectUser(userrec *user)
2279 user->registered = 7;
2280 user->idle_lastmsg = time(NULL);
2281 log(DEBUG,"ConnectUser: %s",user->nick);
2283 if (strcmp(Passwd(user),"") && (!user->haspassed))
2285 kill_link(user,"Invalid password");
2290 kill_link(user,"Unauthorised connection");
2294 char match_against[MAXBUF];
2295 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2296 char* r = matches_gline(match_against);
2299 char reason[MAXBUF];
2300 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2301 kill_link_silent(user,reason);
2305 r = matches_kline(user->host);
2308 char reason[MAXBUF];
2309 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2310 kill_link_silent(user,reason);
2314 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2315 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2316 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2317 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2318 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2319 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);
2320 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);
2322 FOREACH_MOD OnUserConnect(user);
2323 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2325 char buffer[MAXBUF];
2326 snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,ServerName,user->fullname);
2327 NetSendToAll(buffer);
2330 void handle_version(char **parameters, int pcnt, userrec *user)
2332 char Revision[] = "$Revision$";
2334 char *s1 = Revision;
2336 char *v1 = strtok_r(s1," ",&savept);
2338 char *v2 = strtok_r(s1," ",&savept);
2341 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2345 // calls a handler function for a command
2347 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2349 for (int i = 0; i < cmdlist.size(); i++)
2351 if (!strcasecmp(cmdlist[i].command,commandname))
2353 if (cmdlist[i].handler_function)
2355 if (pcnt>=cmdlist[i].min_params)
2357 if (strchr(user->modes,cmdlist[i].flags_needed))
2359 cmdlist[i].handler_function(parameters,pcnt,user);
2367 void DoSplitEveryone()
2369 bool go_again = true;
2373 for (int i = 0; i < 32; i++)
2377 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2379 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2382 j->CloseConnection();
2383 me[i]->connectors.erase(j);
2391 log(DEBUG,"Removed server. Will remove clients...");
2392 // iterate through the userlist and remove all users on this server.
2393 // because we're dealing with a mesh, we dont have to deal with anything
2394 // "down-route" from this server (nice huh)
2396 char reason[MAXBUF];
2400 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2402 if (strcasecmp(u->second->server,ServerName))
2404 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2405 kill_link(u->second,reason);
2415 char islast(const char* s)
2418 for (int j = 0; j < 32; j++)
2422 for (int k = 0; k < me[j]->connectors.size(); k++)
2424 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2428 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2438 long map_count(const char* s)
2441 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2443 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2449 void force_nickchange(userrec* user,const char* newnick)
2456 FOREACH_RESULT(OnUserPreNick(user,newnick));
2458 kill_link(user,"Nickname collision");
2461 if (matches_qline(newnick))
2463 kill_link(user,"Nickname collision");
2471 strncpy(nick,newnick,MAXBUF);
2473 if (user->registered == 7)
2477 handle_nick(pars,1,user);
2483 int process_parameters(char **command_p,char *parameters)
2488 q = strlen(parameters);
2491 /* no parameters, command_p invalid! */
2494 if (parameters[0] == ':')
2496 command_p[0] = parameters+1;
2501 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2503 /* only one parameter */
2504 command_p[0] = parameters;
2505 if (parameters[0] == ':')
2507 if (strchr(parameters,' ') != NULL)
2515 command_p[j++] = parameters;
2516 for (int i = 0; i <= q; i++)
2518 if (parameters[i] == ' ')
2520 command_p[j++] = parameters+i+1;
2521 parameters[i] = '\0';
2522 if (command_p[j-1][0] == ':')
2524 *command_p[j-1]++; /* remove dodgy ":" */
2526 /* parameter like this marks end of the sequence */
2530 return j; /* returns total number of items in the list */
2533 void process_command(userrec *user, char* cmd)
2537 char *command_p[127];
2538 char p[MAXBUF], temp[MAXBUF];
2539 int i, j, items, cmd_found;
2541 for (int i = 0; i < 127; i++)
2542 command_p[i] = NULL;
2552 if (!strcmp(cmd,""))
2557 int total_params = 0;
2560 for (int q = 0; q < strlen(cmd)-1; q++)
2562 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2565 // found a 'trailing', we dont count them after this.
2573 // another phidjit bug...
2574 if (total_params > 126)
2576 kill_link(user,"Protocol violation (1)");
2582 std::string tmp = cmd;
2583 for (int i = 0; i <= MODCOUNT; i++)
2585 std::string oldtmp = tmp;
2586 modules[i]->OnServerRaw(tmp,true);
2589 log(DEBUG,"A Module changed the input string!");
2590 log(DEBUG,"New string: %s",tmp.c_str());
2591 log(DEBUG,"Old string: %s",oldtmp.c_str());
2595 strncpy(cmd,tmp.c_str(),MAXBUF);
2598 if (!strchr(cmd,' '))
2600 /* no parameters, lets skip the formalities and not chop up
2602 log(DEBUG,"About to preprocess command with no params");
2604 command_p[0] = NULL;
2606 for (int i = 0; i <= strlen(cmd); i++)
2608 cmd[i] = toupper(cmd[i]);
2610 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2617 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2618 for (int i = 0; i < strlen(temp); i++)
2620 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2626 /* split the full string into a command plus parameters */
2630 if (strchr(cmd,' '))
2632 for (int i = 0; i <= strlen(cmd); i++)
2634 /* capitalise the command ONLY, leave params intact */
2635 cmd[i] = toupper(cmd[i]);
2636 /* are we nearly there yet?! :P */
2640 parameters = cmd+i+1;
2648 for (int i = 0; i <= strlen(cmd); i++)
2650 cmd[i] = toupper(cmd[i]);
2657 if (strlen(command)>MAXCOMMAND)
2659 kill_link(user,"Protocol violation (2)");
2663 for (int x = 0; x < strlen(command); x++)
2665 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2667 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2669 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2671 kill_link(user,"Protocol violation (3)");
2678 for (int i = 0; i != cmdlist.size(); i++)
2680 if (strcmp(cmdlist[i].command,""))
2682 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2684 log(DEBUG,"Found matching command");
2688 if (strcmp(parameters,""))
2690 items = process_parameters(command_p,parameters);
2695 command_p[0] = NULL;
2701 command_p[0] = NULL;
2706 log(DEBUG,"Processing command");
2708 /* activity resets the ping pending timer */
2709 user->nping = time(NULL) + 120;
2710 if ((items) < cmdlist[i].min_params)
2712 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2713 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2716 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2718 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2719 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2723 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2725 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2727 if ((!isnick(user->nick)) || (user->registered != 7))
2729 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2730 WriteServ(user->fd,"451 %s :You have not registered",command);
2734 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2736 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2737 if (cmdlist[i].handler_function)
2739 /* ikky /stats counters */
2744 user->bytes_in += strlen(temp);
2747 cmdlist[i].use_count++;
2748 cmdlist[i].total_bytes+=strlen(temp);
2751 /* WARNING: nothing may come after the
2752 * command handler call, as the handler
2753 * may free the user structure! */
2755 cmdlist[i].handler_function(command_p,items,user);
2761 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2762 WriteServ(user->fd,"451 %s :You have not registered",command);
2770 if ((!cmd_found) && (user))
2772 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2773 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2778 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2781 /* create the command and push it onto the table */
2782 strcpy(comm.command,cmd);
2783 comm.handler_function = f;
2784 comm.flags_needed = flags;
2785 comm.min_params = minparams;
2787 comm.total_bytes = 0;
2788 cmdlist.push_back(comm);
2789 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2792 void SetupCommandTable(void)
2794 createcommand("USER",handle_user,0,4);
2795 createcommand("NICK",handle_nick,0,1);
2796 createcommand("QUIT",handle_quit,0,0);
2797 createcommand("VERSION",handle_version,0,0);
2798 createcommand("PING",handle_ping,0,1);
2799 createcommand("PONG",handle_pong,0,1);
2800 createcommand("ADMIN",handle_admin,0,0);
2801 createcommand("PRIVMSG",handle_privmsg,0,2);
2802 createcommand("INFO",handle_info,0,0);
2803 createcommand("TIME",handle_time,0,0);
2804 createcommand("WHOIS",handle_whois,0,1);
2805 createcommand("WALLOPS",handle_wallops,'o',1);
2806 createcommand("NOTICE",handle_notice,0,2);
2807 createcommand("JOIN",handle_join,0,1);
2808 createcommand("NAMES",handle_names,0,1);
2809 createcommand("PART",handle_part,0,1);
2810 createcommand("KICK",handle_kick,0,2);
2811 createcommand("MODE",handle_mode,0,1);
2812 createcommand("TOPIC",handle_topic,0,1);
2813 createcommand("WHO",handle_who,0,1);
2814 createcommand("MOTD",handle_motd,0,0);
2815 createcommand("RULES",handle_rules,0,0);
2816 createcommand("OPER",handle_oper,0,2);
2817 createcommand("LIST",handle_list,0,0);
2818 createcommand("DIE",handle_die,'o',1);
2819 createcommand("RESTART",handle_restart,'o',1);
2820 createcommand("KILL",handle_kill,'o',2);
2821 createcommand("REHASH",handle_rehash,'o',0);
2822 createcommand("LUSERS",handle_lusers,0,0);
2823 createcommand("STATS",handle_stats,0,1);
2824 createcommand("USERHOST",handle_userhost,0,1);
2825 createcommand("AWAY",handle_away,0,0);
2826 createcommand("ISON",handle_ison,0,0);
2827 createcommand("SUMMON",handle_summon,0,0);
2828 createcommand("USERS",handle_users,0,0);
2829 createcommand("INVITE",handle_invite,0,2);
2830 createcommand("PASS",handle_pass,0,1);
2831 createcommand("TRACE",handle_trace,'o',0);
2832 createcommand("WHOWAS",handle_whowas,0,1);
2833 createcommand("CONNECT",handle_connect,'o',1);
2834 createcommand("SQUIT",handle_squit,'o',0);
2835 createcommand("MODULES",handle_modules,'o',0);
2836 createcommand("LINKS",handle_links,0,0);
2837 createcommand("MAP",handle_map,0,0);
2838 createcommand("KLINE",handle_kline,'o',1);
2839 createcommand("GLINE",handle_gline,'o',1);
2840 createcommand("ZLINE",handle_zline,'o',1);
2841 createcommand("QLINE",handle_qline,'o',1);
2844 void process_buffer(const char* cmdbuf,userrec *user)
2848 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2855 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2858 if (!strcmp(cmdbuf,""))
2862 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2864 strncpy(cmd,cmdbuf,MAXBUF);
2865 if (!strcmp(cmd,""))
2869 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2871 cmd[strlen(cmd)-1] = '\0';
2873 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2875 cmd[strlen(cmd)-1] = '\0';
2878 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2880 cmd[strlen(cmd)-1] = '\0';
2883 if (!strcmp(cmd,""))
2887 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2889 if ((user) && (cmd))
2891 process_command(user,cmd);
2895 void DoSync(serverrec* serv, char* tcp_host)
2898 log(DEBUG,"Sending sync");
2899 // send start of sync marker: Y <timestamp>
2900 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2901 // except the ones its receiving it from.
2902 snprintf(data,MAXBUF,"Y %d",time(NULL));
2903 serv->SendPacket(data,tcp_host);
2904 // send users and channels
2905 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2907 snprintf(data,MAXBUF,"N %d %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->server,u->second->fullname);
2908 serv->SendPacket(data,tcp_host);
2909 if (strcmp(chlist(u->second),""))
2911 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2912 serv->SendPacket(data,tcp_host);
2915 // send channel modes, topics etc...
2916 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2918 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2919 serv->SendPacket(data,tcp_host);
2920 if (strcmp(c->second->topic,""))
2922 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2923 serv->SendPacket(data,tcp_host);
2925 // send current banlist
2927 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2929 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2930 serv->SendPacket(data,tcp_host);
2933 // sync global zlines, glines, etc
2934 sync_xlines(serv,tcp_host);
2935 snprintf(data,MAXBUF,"F %d",time(NULL));
2936 serv->SendPacket(data,tcp_host);
2937 log(DEBUG,"Sent sync");
2938 // ircd sends its serverlist after the end of sync here
2942 void NetSendMyRoutingTable()
2944 // send out a line saying what is reachable to us.
2945 // E.g. if A is linked to B C and D, send out:
2947 // if its only linked to B and D send out:
2949 // if it has no links, dont even send out the line at all.
2950 char buffer[MAXBUF];
2951 sprintf(buffer,"$ %s",ServerName);
2952 bool sendit = false;
2953 for (int i = 0; i < 32; i++)
2957 for (int j = 0; j < me[i]->connectors.size(); j++)
2959 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2961 strncat(buffer," ",MAXBUF);
2962 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2969 NetSendToAll(buffer);
2973 void DoSplit(const char* params)
2975 bool go_again = true;
2979 for (int i = 0; i < 32; i++)
2983 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2985 if (!strcasecmp(j->GetServerName().c_str(),params))
2988 j->CloseConnection();
2989 me[i]->connectors.erase(j);
2997 log(DEBUG,"Removed server. Will remove clients...");
2998 // iterate through the userlist and remove all users on this server.
2999 // because we're dealing with a mesh, we dont have to deal with anything
3000 // "down-route" from this server (nice huh)
3002 char reason[MAXBUF];
3003 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3007 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3009 if (!strcasecmp(u->second->server,params))
3011 kill_link(u->second,reason);
3019 // removes a server. Will NOT remove its users!
3021 void RemoveServer(const char* name)
3023 bool go_again = true;
3027 for (int i = 0; i < 32; i++)
3031 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3033 if (!strcasecmp(j->GetServerName().c_str(),name))
3036 j->CloseConnection();
3037 me[i]->connectors.erase(j);
3048 int reap_counter = 0;
3052 struct sockaddr_in client, server;
3053 char addrs[MAXBUF][255];
3054 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3056 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3057 int selectResult = 0, selectResult2 = 0;
3058 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3059 char resolvedHost[MAXBUF];
3063 log_file = fopen("ircd.log","a+");
3066 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3070 log(DEBUG,"InspIRCd: startup: begin");
3074 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3076 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3078 SetupCommandTable();
3079 log(DEBUG,"InspIRCd: startup: default command table set up");
3082 if (strcmp(DieValue,""))
3084 printf("WARNING: %s\n\n",DieValue);
3087 log(DEBUG,"InspIRCd: startup: read config");
3089 int count2 = 0, count3 = 0;
3091 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3093 ConfValue("bind","port",count,configToken,&config_f);
3094 ConfValue("bind","address",count,Addr,&config_f);
3095 ConfValue("bind","type",count,Type,&config_f);
3096 if (!strcmp(Type,"servers"))
3098 char Default[MAXBUF];
3099 strcpy(Default,"no");
3100 ConfValue("bind","default",count,Default,&config_f);
3101 if (strchr(Default,'y'))
3103 defaultRoute = count3;
3104 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3106 me[count3] = new serverrec(ServerName,100L,false);
3107 me[count3]->CreateListener(Addr,atoi(configToken));
3112 ports[count2] = atoi(configToken);
3113 strcpy(addrs[count2],Addr);
3116 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3119 UDPportCount = count3;
3121 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3123 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3127 /* BugFix By Craig! :p */
3129 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3131 char modfile[MAXBUF];
3132 ConfValue("module","name",count2,configToken,&config_f);
3133 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3134 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3135 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3136 /* If The File Doesnt exist, Trying to load it
3137 * Will Segfault the IRCd.. So, check to see if
3138 * it Exists, Before Proceeding. */
3139 if (FileExists(modfile))
3141 factory[count] = new ircd_module(modfile);
3142 if (factory[count]->LastError())
3144 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3145 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3148 if (factory[count]->factory)
3150 modules[count] = factory[count]->factory->CreateModule();
3151 /* save the module and the module's classfactory, if
3152 * this isnt done, random crashes can occur :/ */
3153 module_names.push_back(modfile);
3157 log(DEBUG,"Unable to load %s",modfile);
3158 sprintf("Unable to load %s\nExiting...\n",modfile);
3161 /* Increase the Count */
3166 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3167 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3170 MODCOUNT = count - 1;
3171 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3173 printf("\nInspIRCd is now running!\n");
3175 startup_time = time(NULL);
3179 log(VERBOSE,"Not forking as -nofork was specified");
3183 if (DaemonSeed() == ERROR)
3185 log(DEBUG,"InspIRCd: startup: can't daemonise");
3186 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3192 /* setup select call */
3193 FD_ZERO(&selectFds);
3194 log(DEBUG,"InspIRCd: startup: zero selects");
3195 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3197 for (count = 0; count < portCount; count++)
3199 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3201 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3204 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3206 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3208 else /* well we at least bound to one socket so we'll continue */
3214 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3216 /* if we didn't bind to anything then abort */
3217 if (boundPortCount == 0)
3219 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3224 length = sizeof (client);
3225 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3227 /* main loop, this never returns */
3230 #ifdef _POSIX_PRIORITY_SCHEDULING
3233 // update the status of klines, etc
3240 user_hash::iterator count2 = clientlist.begin();
3242 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3243 // them in a list, then reap the list every second or so.
3244 if (reap_counter>300)
3246 if (fd_reap.size() > 0)
3248 for( int n = 0; n < fd_reap.size(); n++)
3250 Blocking(fd_reap[n]);
3252 NonBlocking(fd_reap[n]);
3261 FD_ZERO(&serverfds);
3264 for (int x = 0; x != UDPportCount; x++)
3266 FD_SET(me[x]->fd, &serverfds);
3272 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3275 for (int x = 0; x != UDPportCount; x++)
3277 if (FD_ISSET (me[x]->fd, &serverfds))
3279 char remotehost[MAXBUF],resolved[MAXBUF];
3280 length = sizeof (client);
3281 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3282 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3283 if(CleanAndResolve(resolved, remotehost) != TRUE)
3285 strncpy(resolved,remotehost,MAXBUF);
3287 // add to this connections ircd_connector vector
3288 // *FIX* - we need the LOCAL port not the remote port in &client!
3289 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3294 for (int x = 0; x < UDPportCount; x++)
3296 std::deque<std::string> msgs;
3298 if (me[x]->RecvPacket(msgs, tcp_host))
3300 for (int ctr = 0; ctr < msgs.size(); ctr++)
3302 char udp_msg[MAXBUF];
3303 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3304 if (strlen(udp_msg)<1)
3306 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3309 // during a netburst, send all data to all other linked servers
3310 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3312 if (is_uline(tcp_host))
3314 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3316 NetSendToAllExcept(tcp_host,udp_msg);
3320 NetSendToAllExcept(tcp_host,udp_msg);
3322 FOREACH_MOD OnPacketReceive(udp_msg);
3323 handle_link_packet(udp_msg, tcp_host, me[x]);
3330 while (count2 != clientlist.end())
3333 tval.tv_usec = tval.tv_sec = 0;
3335 int total_in_this_set = 0;
3337 user_hash::iterator xcount = count2;
3338 user_hash::iterator endingiter = count2;
3340 if (!count2->second) break;
3343 if (count2->second->fd != 0)
3345 // assemble up to 64 sockets into an fd_set
3346 // to implement a pooling mechanism.
3348 // This should be up to 64x faster than the
3349 // old implementation.
3350 while (total_in_this_set < 64)
3352 if (count2 != clientlist.end())
3354 // we don't check the state of remote users.
3355 if (count2->second->fd > 0)
3357 FD_SET (count2->second->fd, &sfd);
3359 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3360 // their connection class.
3361 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3363 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3364 kill_link(count2->second,"Registration timeout");
3367 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3369 if ((!count2->second->lastping) && (count2->second->registered == 7))
3371 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3372 kill_link(count2->second,"Ping timeout");
3375 Write(count2->second->fd,"PING :%s",ServerName);
3376 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3377 count2->second->lastping = 0;
3378 count2->second->nping = time(NULL)+120;
3382 total_in_this_set++;
3387 endingiter = count2;
3388 count2 = xcount; // roll back to where we were
3394 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3396 // now loop through all of the items in this pool if any are waiting
3397 //if (selectResult2 > 0)
3398 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3401 #ifdef _POSIX_PRIORITY_SCHEDULING
3406 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3408 log(DEBUG,"Reading fd %d",count2a->second->fd);
3409 memset(data, 0, 10240);
3410 result = read(count2a->second->fd, data, 10240);
3415 log(DEBUG,"Read %d characters from socket",result);
3416 userrec* current = count2a->second;
3417 int currfd = current->fd;
3418 char* l = strtok(data,"\n");
3423 if ((floodlines > current->flood) && (current->flood != 0))
3425 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3426 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3427 kill_link(current,"Excess flood");
3430 char sanitized[NetBufferSize];
3431 memset(sanitized, 0, NetBufferSize);
3433 for (int pt = 0; pt < strlen(l); pt++)
3437 sanitized[ptt++] = l[pt];
3440 sanitized[ptt] = '\0';
3441 if (strlen(sanitized))
3445 // we're gonna re-scan to check if the nick is gone, after every
3446 // command - if it has, we're gonna bail
3447 bool find_again = false;
3448 process_buffer(sanitized,current);
3450 // look for the user's record in case it's changed
3451 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3453 if (c2->second->fd == currfd)
3455 // found again, update pointer
3456 current == c2->second;
3465 l = strtok(NULL,"\n");
3470 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3472 log(DEBUG,"killing: %s",count2a->second->nick);
3473 kill_link(count2a->second,strerror(errno));
3477 // result EAGAIN means nothing read
3478 if (result == EAGAIN)
3486 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3487 kill_link(count2a->second,"Client exited");
3488 // must bail here? kill_link removes the hash, corrupting the iterator
3489 log(DEBUG,"Bailing from client exit");
3493 else if (result > 0)
3498 for (int q = 0; q < total_in_this_set; q++)
3500 // there is no iterator += operator :(
3501 //if (count2 != clientlist.end())
3508 // set up select call
3509 for (count = 0; count < boundPortCount; count++)
3511 FD_SET (openSockfd[count], &selectFds);
3515 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3517 /* select is reporting a waiting socket. Poll them all to find out which */
3518 if (selectResult > 0)
3520 char target[MAXBUF], resolved[MAXBUF];
3521 for (count = 0; count < boundPortCount; count++)
3523 if (FD_ISSET (openSockfd[count], &selectFds))
3525 length = sizeof (client);
3526 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3528 address_cache::iterator iter = IP.find(client.sin_addr);
3529 bool iscached = false;
3530 if (iter == IP.end())
3532 /* ip isn't in cache, add it */
3533 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3534 if(CleanAndResolve(resolved, target) != TRUE)
3536 strncpy(resolved,target,MAXBUF);
3538 /* hostname now in 'target' */
3539 IP[client.sin_addr] = new string(resolved);
3540 /* hostname in cache */
3544 /* found ip (cached) */
3545 strncpy(resolved, iter->second->c_str(), MAXBUF);
3549 if (incomingSockfd < 0)
3551 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3552 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3556 AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3557 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3564 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3567 close (incomingSockfd);