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
87 extern vector<Module*> modules;
88 std::vector<std::string> module_names;
89 extern vector<ircd_module*> factory;
90 std::vector<int> fd_reap;
98 template<> struct nspace::hash<in_addr>
100 size_t operator()(const struct in_addr &a) const
103 memcpy(&q,&a,sizeof(size_t));
108 template<> struct nspace::hash<string>
110 size_t operator()(const string &s) const
113 static struct hash<const char *> strhash;
125 bool operator()(const string& s1, const string& s2) const
127 char a[MAXBUF],b[MAXBUF];
128 strcpy(a,s1.c_str());
129 strcpy(b,s2.c_str());
130 return (strcasecmp(a,b) == 0);
135 struct InAddr_HashComp
138 bool operator()(const in_addr &s1, const in_addr &s2) const
143 memcpy(&q,&s1,sizeof(size_t));
144 memcpy(&p,&s2,sizeof(size_t));
152 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
153 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
154 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
155 typedef std::deque<command_t> command_table;
161 user_hash clientlist;
164 command_table cmdlist;
171 struct linger linger = { 0 };
172 char bannerBuffer[MAXBUF];
173 int boundPortCount = 0;
174 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
175 int defaultRoute = 0;
179 long MyKey = C.GenKey();
183 int has_channel(userrec *u, chanrec *c);
184 int usercount(chanrec *c);
185 int usercount_i(chanrec *c);
186 void update_stats_l(int fd,int data_out);
187 char* Passwd(userrec *user);
188 bool IsDenied(userrec *user);
189 void AddWhoWas(userrec* u);
191 std::vector<long> auth_cookies;
192 std::stringstream config_f(stringstream::in | stringstream::out);
198 char Revision[] = "$Revision$";
201 char *v1 = strtok_r(s1," ",&savept);
203 char *v2 = strtok_r(s1," ",&savept);
205 return (long)(atof(v2)*10000);
209 std::string getservername()
214 std::string getserverdesc()
219 std::string getnetworkname()
224 std::string getadminname()
229 std::string getadminemail()
234 std::string getadminnick()
239 void log(int level,char *text, ...)
241 char textbuffer[MAXBUF];
244 struct tm * timeinfo;
245 if (level < LogLevel)
249 timeinfo = localtime (&rawtime);
254 va_start (argsPtr, text);
255 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
257 strcpy(b,asctime(timeinfo));
258 b[strlen(b)-1] = ':';
259 fprintf(log_file,"%s %s\n",b,textbuffer);
262 // nofork enabled? display it on terminal too
263 printf("%s %s\n",b,textbuffer);
268 void readfile(file_cache &F, const char* fname)
271 char linebuf[MAXBUF];
273 log(DEBUG,"readfile: loading %s",fname);
275 file = fopen(fname,"r");
280 fgets(linebuf,sizeof(linebuf),file);
281 linebuf[strlen(linebuf)-1]='\0';
282 if (!strcmp(linebuf,""))
288 F.push_back(linebuf);
295 log(DEBUG,"readfile: failed to load file: %s",fname);
297 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
300 void ReadConfig(void)
302 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
305 LoadConf(CONFIG_FILE,&config_f);
307 ConfValue("server","name",0,ServerName,&config_f);
308 ConfValue("server","description",0,ServerDesc,&config_f);
309 ConfValue("server","network",0,Network,&config_f);
310 ConfValue("admin","name",0,AdminName,&config_f);
311 ConfValue("admin","email",0,AdminEmail,&config_f);
312 ConfValue("admin","nick",0,AdminNick,&config_f);
313 ConfValue("files","motd",0,motd,&config_f);
314 ConfValue("files","rules",0,rules,&config_f);
315 ConfValue("power","diepass",0,diepass,&config_f);
316 ConfValue("power","pause",0,pauseval,&config_f);
317 ConfValue("power","restartpass",0,restartpass,&config_f);
318 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
319 ConfValue("die","value",0,DieValue,&config_f);
320 ConfValue("options","loglevel",0,dbg,&config_f);
321 ConfValue("options","netbuffersize",0,NB,&config_f);
322 NetBufferSize = atoi(NB);
323 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
325 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
326 NetBufferSize = 10240;
328 if (!strcmp(dbg,"debug"))
330 if (!strcmp(dbg,"verbose"))
332 if (!strcmp(dbg,"default"))
334 if (!strcmp(dbg,"sparse"))
336 if (!strcmp(dbg,"none"))
339 log(DEFAULT,"Reading message of the day...");
340 readfile(RULES,rules);
341 log(DEFAULT,"Reading connect classes...");
343 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
346 ConfValue("connect","allow",i,Value,&config_f);
347 ConfValue("connect","timeout",i,timeout,&config_f);
348 ConfValue("connect","flood",i,flood,&config_f);
349 if (strcmp(Value,""))
351 strcpy(c.host,Value);
354 ConfValue("connect","password",i,Value,&config_f);
355 strcpy(c.pass,Value);
356 c.registration_timeout = 90; // default is 2 minutes
357 c.flood = atoi(flood);
360 c.registration_timeout = atoi(timeout);
362 Classes.push_back(c);
363 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
367 ConfValue("connect","deny",i,Value,&config_f);
368 strcpy(c.host,Value);
370 Classes.push_back(c);
371 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
375 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
376 read_xline_defaults();
377 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
379 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
382 /* write formatted text to a socket, in same format as printf */
384 void Write(int sock,char *text, ...)
388 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
391 char textbuffer[MAXBUF];
395 va_start (argsPtr, text);
396 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
398 sprintf(tb,"%s\r\n",textbuffer);
402 write(sock,tb,strlen(tb));
403 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
407 /* write a server formatted numeric response to a single socket */
409 void WriteServ(int sock, char* text, ...)
413 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
416 char textbuffer[MAXBUF],tb[MAXBUF];
418 va_start (argsPtr, text);
420 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
422 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
426 write(sock,tb,strlen(tb));
427 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
431 /* write text from an originating user to originating user */
433 void WriteFrom(int sock, userrec *user,char* text, ...)
435 if ((!text) || (!user))
437 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
440 char textbuffer[MAXBUF],tb[MAXBUF];
442 va_start (argsPtr, text);
444 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
446 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
450 write(sock,tb,strlen(tb));
451 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
455 /* write text to an destination user from a source user (e.g. user privmsg) */
457 void WriteTo(userrec *source, userrec *dest,char *data, ...)
459 if ((!dest) || (!data))
461 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
464 char textbuffer[MAXBUF],tb[MAXBUF];
466 va_start (argsPtr, data);
467 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
471 // if no source given send it from the server.
474 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
478 WriteFrom(dest->fd,source,"%s",textbuffer);
482 /* write formatted text from a source user to all users on a channel
483 * including the sender (NOT for privmsg, notice etc!) */
485 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
487 if ((!Ptr) || (!user) || (!text))
489 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
492 char textbuffer[MAXBUF];
494 va_start (argsPtr, text);
495 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
497 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
499 if (has_channel(i->second,Ptr))
501 WriteTo(user,i->second,"%s",textbuffer);
506 /* write formatted text from a source user to all users on a channel
507 * including the sender (NOT for privmsg, notice etc!) doesnt send to
508 * users on remote servers */
510 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
512 if ((!Ptr) || (!text))
514 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
517 char textbuffer[MAXBUF];
519 va_start (argsPtr, text);
520 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
522 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
524 if (has_channel(i->second,Ptr))
526 if (i->second->fd != -1)
530 WriteServ(i->second->fd,"%s",textbuffer);
534 WriteTo(user,i->second,"%s",textbuffer);
542 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
544 if ((!Ptr) || (!user) || (!text))
546 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
549 char textbuffer[MAXBUF];
551 va_start (argsPtr, text);
552 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
554 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
558 if (has_channel(i->second,Ptr))
560 WriteServ(i->second->fd,"%s",textbuffer);
567 /* write formatted text from a source user to all users on a channel except
568 * for the sender (for privmsg etc) */
570 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
572 if ((!Ptr) || (!user) || (!text))
574 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
577 char textbuffer[MAXBUF];
579 va_start (argsPtr, text);
580 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
583 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
587 if (has_channel(i->second,Ptr) && (user != i->second))
589 WriteTo(user,i->second,"%s",textbuffer);
596 std::string GetServerDescription(char* servername)
598 for (int j = 0; j < 32; j++)
602 for (int k = 0; k < me[j]->connectors.size(); k++)
604 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
606 return me[j]->connectors[k].GetDescription();
610 return ServerDesc; // not a remote server that can be found, it must be me.
615 /* write a formatted string to all users who share at least one common
616 * channel, including the source user e.g. for use in NICK */
618 void WriteCommon(userrec *u, char* text, ...)
622 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
626 if (u->registered != 7) {
627 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
631 char textbuffer[MAXBUF];
633 va_start (argsPtr, text);
634 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
637 WriteFrom(u->fd,u,"%s",textbuffer);
639 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
643 if (common_channels(u,i->second) && (i->second != u))
645 WriteFrom(i->second->fd,u,"%s",textbuffer);
651 /* write a formatted string to all users who share at least one common
652 * channel, NOT including the source user e.g. for use in QUIT */
654 void WriteCommonExcept(userrec *u, char* text, ...)
658 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
662 if (u->registered != 7) {
663 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
667 char textbuffer[MAXBUF];
669 va_start (argsPtr, text);
670 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
673 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
677 if ((common_channels(u,i->second)) && (u != i->second))
679 WriteFrom(i->second->fd,u,"%s",textbuffer);
685 void WriteOpers(char* text, ...)
689 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
693 char textbuffer[MAXBUF];
695 va_start (argsPtr, text);
696 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
699 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
703 if (strchr(i->second->modes,'o'))
705 if (strchr(i->second->modes,'s'))
707 // send server notices to all with +s
708 // (TODO: needs SNOMASKs)
709 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
716 // returns TRUE of any users on channel C occupy server 'servername'.
718 bool ChanAnyOnThisServer(chanrec *c,char* servername)
720 log(DEBUG,"ChanAnyOnThisServer");
721 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
723 if (has_channel(i->second,c))
725 if (!strcasecmp(i->second->server,servername))
734 // returns true if user 'u' shares any common channels with any users on server 'servername'
736 bool CommonOnThisServer(userrec* u,const char* servername)
738 log(DEBUG,"ChanAnyOnThisServer");
739 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
741 if ((common_channels(u,i->second)) && (u != i->second))
743 if (!strcasecmp(i->second->server,servername))
745 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
754 void NetSendToCommon(userrec* u, char* s)
757 snprintf(buffer,MAXBUF,"%s",s);
759 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
761 for (int j = 0; j < 32; j++)
765 for (int k = 0; k < me[j]->connectors.size(); k++)
767 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
769 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
777 void NetSendToAll(char* s)
780 snprintf(buffer,MAXBUF,"%s",s);
782 log(DEBUG,"NetSendToAll: '%s'",s);
784 for (int j = 0; j < 32; j++)
788 for (int k = 0; k < me[j]->connectors.size(); k++)
790 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
796 void NetSendToAllAlive(char* s)
799 snprintf(buffer,MAXBUF,"%s",s);
801 log(DEBUG,"NetSendToAllAlive: '%s'",s);
803 for (int j = 0; j < 32; j++)
807 for (int k = 0; k < me[j]->connectors.size(); k++)
809 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
811 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
815 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
823 void NetSendToOne(char* target,char* s)
826 snprintf(buffer,MAXBUF,"%s",s);
828 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
830 for (int j = 0; j < 32; j++)
834 for (int k = 0; k < me[j]->connectors.size(); k++)
836 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
838 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
845 void NetSendToAllExcept(const char* target,char* s)
848 snprintf(buffer,MAXBUF,"%s",s);
850 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
852 for (int j = 0; j < 32; j++)
856 for (int k = 0; k < me[j]->connectors.size(); k++)
858 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
860 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
868 void WriteMode(const char* modes, int flags, const char* text, ...)
870 if ((!text) || (!modes) || (!flags))
872 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
876 char textbuffer[MAXBUF];
878 va_start (argsPtr, text);
879 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
882 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
886 bool send_to_user = false;
891 for (int n = 0; n < strlen(modes); n++)
893 if (!hasumode(i->second,modes[n]))
895 send_to_user = false;
900 else if (flags == WM_OR)
902 send_to_user = false;
903 for (int n = 0; n < strlen(modes); n++)
905 if (hasumode(i->second,modes[n]))
915 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
922 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
924 if ((!text) || (!source))
926 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
931 char textbuffer[MAXBUF];
933 va_start (argsPtr, text);
934 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
937 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
941 if (strchr(i->second->modes,'w'))
943 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
951 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
952 NetSendToAll(buffer);
956 /* convert a string to lowercase. Note following special circumstances
957 * taken from RFC 1459. Many "official" server branches still hold to this
958 * rule so i will too;
960 * Because of IRC's scandanavian origin, the characters {}| are
961 * considered to be the lower case equivalents of the characters []\,
962 * respectively. This is a critical issue when determining the
963 * equivalence of two nicknames.
966 void strlower(char *n)
972 for (int i = 0; i != strlen(n); i++)
974 n[i] = tolower(n[i]);
986 /* Find a user record by nickname and return a pointer to it */
988 userrec* Find(string nick)
990 user_hash::iterator iter = clientlist.find(nick);
992 if (iter == clientlist.end())
993 /* Couldn't find it */
999 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1001 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1005 if (i->second->fd == fd)
1007 i->second->bytes_out+=data_out;
1008 i->second->cmds_out++;
1015 /* find a channel record by channel name and return a pointer to it */
1017 chanrec* FindChan(const char* chan)
1021 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1025 chan_hash::iterator iter = chanlist.find(chan);
1027 if (iter == chanlist.end())
1028 /* Couldn't find it */
1031 return iter->second;
1035 void purge_empty_chans(void)
1037 int go_again = 1, purge = 0;
1042 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1045 if (!usercount(i->second))
1047 /* kill the record */
1048 if (i != chanlist.end())
1050 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1060 log(DEBUG,"skipped purge for %s",i->second->name);
1065 log(DEBUG,"completed channel purge, killed %d",purge);
1069 char scratch[MAXBUF];
1070 char sparam[MAXBUF];
1072 char* chanmodes(chanrec *chan)
1076 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1083 if (chan->noexternal)
1085 strncat(scratch,"n",MAXMODES);
1087 if (chan->topiclock)
1089 strncat(scratch,"t",MAXMODES);
1091 if (strcmp(chan->key,""))
1093 strncat(scratch,"k",MAXMODES);
1097 strncat(scratch,"l",MAXMODES);
1099 if (chan->inviteonly)
1101 strncat(scratch,"i",MAXMODES);
1103 if (chan->moderated)
1105 strncat(scratch,"m",MAXMODES);
1109 strncat(scratch,"s",MAXMODES);
1111 if (chan->c_private)
1113 strncat(scratch,"p",MAXMODES);
1115 if (strcmp(chan->key,""))
1117 strncat(sparam,chan->key,MAXBUF);
1122 sprintf(foo," %d",chan->limit);
1123 strncat(sparam,foo,MAXBUF);
1125 if (strlen(chan->custom_modes))
1127 strncat(scratch,chan->custom_modes,MAXMODES);
1128 for (int z = 0; z < strlen(chan->custom_modes); z++)
1130 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1133 strncat(sparam," ",MAXBUF);
1134 strncat(sparam,extparam.c_str(),MAXBUF);
1138 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1139 strncat(scratch,sparam,MAXMODES);
1144 /* compile a userlist of a channel into a string, each nick seperated by
1145 * spaces and op, voice etc status shown as @ and + */
1147 void userlist(userrec *user,chanrec *c)
1149 if ((!c) || (!user))
1151 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1155 sprintf(list,"353 %s = %s :", user->nick, c->name);
1156 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1158 if (has_channel(i->second,c))
1160 if (isnick(i->second->nick))
1162 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1164 /* user is +i, and source not on the channel, does not show
1165 * nick in NAMES list */
1168 strcat(list,cmode(i->second,c));
1169 strcat(list,i->second->nick);
1171 if (strlen(list)>(480-NICKMAX))
1173 /* list overflowed into
1174 * multiple numerics */
1175 WriteServ(user->fd,list);
1176 sprintf(list,"353 %s = %s :", user->nick, c->name);
1181 /* if whats left in the list isnt empty, send it */
1182 if (list[strlen(list)-1] != ':')
1184 WriteServ(user->fd,list);
1188 /* return a count of the users on a specific channel accounting for
1189 * invisible users who won't increase the count. e.g. for /LIST */
1191 int usercount_i(chanrec *c)
1198 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1203 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1207 if (has_channel(i->second,c))
1209 if (isnick(i->second->nick))
1211 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1213 /* user is +i, and source not on the channel, does not show
1214 * nick in NAMES list */
1222 log(DEBUG,"usercount_i: %s %d",c->name,count);
1227 int usercount(chanrec *c)
1234 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1239 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1243 if (has_channel(i->second,c))
1245 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1252 log(DEBUG,"usercount: %s %d",c->name,count);
1257 /* add a channel to a user, creating the record for it if needed and linking
1258 * it to the user record */
1260 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1262 if ((!user) || (!cn))
1264 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1273 strncpy(cname,cn,MAXBUF);
1275 // we MUST declare this wherever we use FOREACH_RESULT
1278 if (strlen(cname) > CHANMAX-1)
1280 cname[CHANMAX-1] = '\0';
1283 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1285 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1287 return NULL; // already on the channel!
1291 if (!FindChan(cname))
1293 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1298 /* create a new one */
1299 log(DEBUG,"add_channel: creating: %s",cname);
1301 chanlist[cname] = new chanrec();
1303 strcpy(chanlist[cname]->name, cname);
1304 chanlist[cname]->topiclock = 1;
1305 chanlist[cname]->noexternal = 1;
1306 chanlist[cname]->created = time(NULL);
1307 strcpy(chanlist[cname]->topic, "");
1308 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1309 chanlist[cname]->topicset = 0;
1310 Ptr = chanlist[cname];
1311 log(DEBUG,"add_channel: created: %s",cname);
1312 /* set created to 2 to indicate user
1313 * is the first in the channel
1314 * and should be given ops */
1320 /* channel exists, just fish out a pointer to its struct */
1321 Ptr = FindChan(cname);
1324 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1326 // the override flag allows us to bypass channel modes
1327 // and bans (used by servers)
1330 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1335 if (strcmp(Ptr->key,""))
1337 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1340 log(DEBUG,"add_channel: no key given in JOIN");
1341 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1346 log(DEBUG,"key at %p is %s",key,key);
1347 if (strcasecmp(key,Ptr->key))
1349 log(DEBUG,"add_channel: bad key given in JOIN");
1350 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1355 log(DEBUG,"add_channel: no key");
1357 if (Ptr->inviteonly)
1359 log(DEBUG,"add_channel: channel is +i");
1360 if (user->IsInvited(Ptr->name))
1362 /* user was invited to channel */
1363 /* there may be an optional channel NOTICE here */
1367 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1371 log(DEBUG,"add_channel: channel is not +i");
1375 if (usercount(Ptr) == Ptr->limit)
1377 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1382 log(DEBUG,"add_channel: about to walk banlist");
1384 /* check user against the channel banlist */
1387 if (Ptr->bans.size())
1389 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1391 if (match(user->GetFullHost(),i->data))
1393 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1400 log(DEBUG,"add_channel: bans checked");
1403 if ((Ptr) && (user))
1405 user->RemoveInvite(Ptr->name);
1408 log(DEBUG,"add_channel: invites removed");
1413 log(DEBUG,"Overridden checks");
1421 log(DEBUG,"Passed channel checks");
1423 for (int i =0; i != MAXCHANS; i++)
1425 log(DEBUG,"Check location %d",i);
1426 if (user->chans[i].channel == NULL)
1428 log(DEBUG,"Adding into their channel list at location %d",i);
1432 /* first user in is given ops */
1433 user->chans[i].uc_modes = UCMODE_OP;
1437 user->chans[i].uc_modes = 0;
1439 user->chans[i].channel = Ptr;
1440 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1442 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1444 // use the stamdard J token with no privilages.
1445 char buffer[MAXBUF];
1446 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1447 NetSendToAll(buffer);
1450 log(DEBUG,"Sent JOIN to client");
1454 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1455 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1458 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1459 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1460 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1461 FOREACH_MOD OnUserJoin(user,Ptr);
1465 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1466 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1470 /* remove a channel from a users record, and remove the record from memory
1471 * if the channel has become empty */
1473 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1475 if ((!user) || (!cname))
1477 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1484 if ((!cname) || (!user))
1489 Ptr = FindChan(cname);
1496 FOREACH_MOD OnUserPart(user,Ptr);
1497 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1499 for (int i =0; i != MAXCHANS; i++)
1501 /* zap it from the channel list of the user */
1502 if (user->chans[i].channel == Ptr)
1506 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1510 char buffer[MAXBUF];
1511 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1512 NetSendToAll(buffer);
1521 char buffer[MAXBUF];
1522 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1523 NetSendToAll(buffer);
1526 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1528 user->chans[i].uc_modes = 0;
1529 user->chans[i].channel = NULL;
1530 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1535 /* if there are no users left on the channel */
1536 if (!usercount(Ptr))
1538 chan_hash::iterator iter = chanlist.find(Ptr->name);
1540 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1542 /* kill the record */
1543 if (iter != chanlist.end())
1545 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1546 delete iter->second;
1547 chanlist.erase(iter);
1553 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1555 if ((!src) || (!user) || (!Ptr) || (!reason))
1557 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1564 if ((!Ptr) || (!user) || (!src))
1569 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1571 if (!has_channel(user,Ptr))
1573 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1576 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1578 if (cstatus(src,Ptr) == STATUS_HOP)
1580 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1584 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1590 for (int i =0; i != MAXCHANS; i++)
1592 /* zap it from the channel list of the user */
1593 if (user->chans[i].channel)
1594 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1596 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1597 user->chans[i].uc_modes = 0;
1598 user->chans[i].channel = NULL;
1599 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1604 /* if there are no users left on the channel */
1605 if (!usercount(Ptr))
1607 chan_hash::iterator iter = chanlist.find(Ptr->name);
1609 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1611 /* kill the record */
1612 if (iter != chanlist.end())
1614 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1615 delete iter->second;
1616 chanlist.erase(iter);
1624 /* This function pokes and hacks at a parameter list like the following:
1626 * PART #winbot, #darkgalaxy :m00!
1628 * to turn it into a series of individual calls like this:
1630 * PART #winbot :m00!
1631 * PART #darkgalaxy :m00!
1633 * The seperate calls are sent to a callback function provided by the caller
1634 * (the caller will usually call itself recursively). The callback function
1635 * must be a command handler. Calling this function on a line with no list causes
1636 * no action to be taken. You must provide a starting and ending parameter number
1637 * where the range of the list can be found, useful if you have a terminating
1638 * parameter as above which is actually not part of the list, or parameters
1639 * before the actual list as well. This code is used by many functions which
1640 * can function as "one to list" (see the RFC) */
1642 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1647 char blog[32][MAXBUF];
1648 char blog2[32][MAXBUF];
1649 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1650 char keystr[MAXBUF];
1653 for (int i = 0; i <32; i++)
1656 for (int i = 0; i <32; i++)
1657 strcpy(blog2[i],"");
1660 for (int i = 0; i <10; i++)
1664 parameters[i] = moo;
1669 if (pcnt > 1) /* we have a key to copy */
1671 strcpy(keystr,parameters[1]);
1675 if (!parameters[start])
1679 if (!strchr(parameters[start],','))
1684 for (int i = start; i <= end; i++)
1688 strcat(plist,parameters[i]);
1696 for (int i = 0; i < t; i++)
1698 if (plist[i] == ',')
1701 strcpy(blog[j++],param);
1705 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1710 strcpy(blog[j++],param);
1713 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1718 if ((joins) && (keystr))
1720 if (strchr(keystr,','))
1724 t2 = strlen(keystr);
1725 for (int i = 0; i < t2; i++)
1727 if (keystr[i] == ',')
1730 strcpy(blog2[j++],param);
1734 strcpy(blog2[j++],param);
1739 for (j = 0; j < total; j++)
1745 for (q = end; q < pcnt-1; q++)
1747 if (parameters[q+1])
1749 pars[q-end+1] = parameters[q+1];
1752 if ((joins) && (parameters[1]))
1763 /* repeatedly call the function with the hacked parameter list */
1764 if ((joins) && (pcnt > 1))
1768 // pars[1] already set up and containing key from blog2[j]
1773 pars[1] = parameters[1];
1779 fn(pars,pcnt-(end-start),u);
1788 void kill_link(userrec *user,const char* r)
1790 user_hash::iterator iter = clientlist.find(user->nick);
1792 char reason[MAXBUF];
1794 strncpy(reason,r,MAXBUF);
1796 if (strlen(reason)>MAXQUIT)
1798 reason[MAXQUIT-1] = '\0';
1801 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1802 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1803 log(DEBUG,"closing fd %d",user->fd);
1805 /* bugfix, cant close() a nonblocking socket (sux!) */
1806 if (user->registered == 7) {
1807 FOREACH_MOD OnUserQuit(user);
1808 WriteCommonExcept(user,"QUIT :%s",reason);
1810 // Q token must go to ALL servers!!!
1811 char buffer[MAXBUF];
1812 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1813 NetSendToAll(buffer);
1816 /* push the socket on a stack of sockets due to be closed at the next opportunity
1817 * 'Client exited' is an exception to this as it means the client side has already
1818 * closed the socket, we don't need to do it.
1820 fd_reap.push_back(user->fd);
1822 bool do_purge = false;
1824 if (user->registered == 7) {
1825 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1829 if (iter != clientlist.end())
1831 log(DEBUG,"deleting user hash value %d",iter->second);
1832 if ((iter->second) && (user->registered == 7)) {
1833 delete iter->second;
1835 clientlist.erase(iter);
1838 if (user->registered == 7) {
1839 purge_empty_chans();
1845 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1847 char* Passwd(userrec *user)
1849 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1851 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1859 bool IsDenied(userrec *user)
1861 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1863 if (match(user->host,i->host) && (i->type == CC_DENY))
1874 /* sends out an error notice to all connected clients (not to be used
1877 void send_error(char *s)
1879 log(DEBUG,"send_error: %s",s);
1880 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1882 if (isnick(i->second->nick))
1884 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1888 // fix - unregistered connections receive ERROR, not NOTICE
1889 Write(i->second->fd,"ERROR :%s",s);
1894 void Error(int status)
1896 signal (SIGALRM, SIG_IGN);
1897 signal (SIGPIPE, SIG_IGN);
1898 signal (SIGTERM, SIG_IGN);
1899 signal (SIGABRT, SIG_IGN);
1900 signal (SIGSEGV, SIG_IGN);
1901 signal (SIGURG, SIG_IGN);
1902 signal (SIGKILL, SIG_IGN);
1903 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1904 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1909 int main(int argc, char *argv[])
1913 log(DEBUG,"*** InspIRCd starting up!");
1914 if (!FileExists(CONFIG_FILE))
1916 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1917 log(DEBUG,"main: no config");
1918 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1922 if (!strcmp(argv[1],"-nofork")) {
1926 if (InspIRCd() == ERROR)
1928 log(DEBUG,"main: daemon function bailed");
1929 printf("ERROR: could not initialise. Shutting down.\n");
1936 template<typename T> inline string ConvToStr(const T &in)
1939 if (!(tmp << in)) return string();
1943 /* re-allocates a nick in the user_hash after they change nicknames,
1944 * returns a pointer to the new user as it may have moved */
1946 userrec* ReHashNick(char* Old, char* New)
1948 user_hash::iterator newnick;
1949 user_hash::iterator oldnick = clientlist.find(Old);
1951 log(DEBUG,"ReHashNick: %s %s",Old,New);
1953 if (!strcasecmp(Old,New))
1955 log(DEBUG,"old nick is new nick, skipping");
1956 return oldnick->second;
1959 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1961 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1963 clientlist[New] = new userrec();
1964 clientlist[New] = oldnick->second;
1965 /*delete oldnick->second; */
1966 clientlist.erase(oldnick);
1968 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1970 return clientlist[New];
1973 /* adds or updates an entry in the whowas list */
1974 void AddWhoWas(userrec* u)
1976 user_hash::iterator iter = whowas.find(u->nick);
1977 userrec *a = new userrec();
1978 strcpy(a->nick,u->nick);
1979 strcpy(a->ident,u->ident);
1980 strcpy(a->dhost,u->dhost);
1981 strcpy(a->host,u->host);
1982 strcpy(a->fullname,u->fullname);
1983 strcpy(a->server,u->server);
1984 a->signon = u->signon;
1986 /* MAX_WHOWAS: max number of /WHOWAS items
1987 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1988 * can be replaced by a newer one
1991 if (iter == whowas.end())
1993 if (whowas.size() == WHOWAS_MAX)
1995 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1997 // 3600 seconds in an hour ;)
1998 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2002 log(DEBUG,"added WHOWAS entry, purged an old record");
2009 log(DEBUG,"added fresh WHOWAS entry");
2010 whowas[a->nick] = a;
2015 log(DEBUG,"updated WHOWAS entry");
2016 delete iter->second;
2022 /* add a client connection to the sockets list */
2023 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2027 char resolved[MAXBUF];
2030 user_hash::iterator iter;
2032 tempnick = ConvToStr(socket) + "-unknown";
2033 sprintf(tn2,"%d-unknown",socket);
2035 iter = clientlist.find(tempnick);
2037 if (iter != clientlist.end()) return;
2040 * It is OK to access the value here this way since we know
2041 * it exists, we just created it above.
2043 * At NO other time should you access a value in a map or a
2044 * hash_map this way.
2046 clientlist[tempnick] = new userrec();
2048 NonBlocking(socket);
2049 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
2051 clientlist[tempnick]->fd = socket;
2052 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2053 strncpy(clientlist[tempnick]->host, host,160);
2054 strncpy(clientlist[tempnick]->dhost, host,160);
2055 strncpy(clientlist[tempnick]->server, ServerName,256);
2056 strncpy(clientlist[tempnick]->ident, "unknown",9);
2057 clientlist[tempnick]->registered = 0;
2058 clientlist[tempnick]->signon = time(NULL);
2059 clientlist[tempnick]->nping = time(NULL)+240;
2060 clientlist[tempnick]->lastping = 1;
2061 clientlist[tempnick]->port = port;
2062 strncpy(clientlist[tempnick]->ip,ip,32);
2066 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2070 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2073 // set the registration timeout for this user
2074 unsigned long class_regtimeout = 90;
2075 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2077 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2079 class_regtimeout = (unsigned long)i->registration_timeout;
2084 int class_flood = 0;
2085 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2087 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2089 class_flood = i->flood;
2094 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2095 clientlist[tempnick]->flood = class_flood;
2097 for (int i = 0; i < MAXCHANS; i++)
2099 clientlist[tempnick]->chans[i].channel = NULL;
2100 clientlist[tempnick]->chans[i].uc_modes = 0;
2103 if (clientlist.size() == MAXCLIENTS)
2104 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2106 char* r = matches_zline(ip);
2109 char reason[MAXBUF];
2110 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2111 kill_link(clientlist[tempnick],reason);
2118 return clientlist.size();
2122 int usercount_invisible(void)
2126 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2128 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2133 int usercount_opers(void)
2137 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2139 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2144 int usercount_unknown(void)
2148 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2150 if ((i->second->fd) && (i->second->registered != 7))
2156 long chancount(void)
2158 return chanlist.size();
2161 long count_servs(void)
2164 //for (int j = 0; j < 255; j++)
2166 // if (servers[j] != NULL)
2172 long servercount(void)
2174 return count_servs()+1;
2180 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2182 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2188 void ShowMOTD(userrec *user)
2192 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2195 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2196 for (int i = 0; i != MOTD.size(); i++)
2198 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2200 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2203 void ShowRULES(userrec *user)
2207 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2210 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2211 for (int i = 0; i != RULES.size(); i++)
2213 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2215 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2218 /* shows the message of the day, and any other on-logon stuff */
2219 void ConnectUser(userrec *user)
2221 user->registered = 7;
2222 user->idle_lastmsg = time(NULL);
2223 log(DEBUG,"ConnectUser: %s",user->nick);
2225 if (strcmp(Passwd(user),"") && (!user->haspassed))
2227 kill_link(user,"Invalid password");
2232 kill_link(user,"Unauthorised connection");
2236 char match_against[MAXBUF];
2237 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2238 char* r = matches_gline(match_against);
2241 char reason[MAXBUF];
2242 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2243 kill_link(user,reason);
2247 r = matches_kline(user->host);
2250 char reason[MAXBUF];
2251 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2252 kill_link(user,reason);
2256 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2257 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2258 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2259 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2260 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2261 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);
2262 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);
2264 FOREACH_MOD OnUserConnect(user);
2265 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2267 char buffer[MAXBUF];
2268 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);
2269 NetSendToAll(buffer);
2272 void handle_version(char **parameters, int pcnt, userrec *user)
2274 char Revision[] = "$Revision$";
2276 char *s1 = Revision;
2278 char *v1 = strtok_r(s1," ",&savept);
2280 char *v2 = strtok_r(s1," ",&savept);
2283 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2287 // calls a handler function for a command
2289 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2291 for (int i = 0; i < cmdlist.size(); i++)
2293 if (!strcasecmp(cmdlist[i].command,commandname))
2295 if (cmdlist[i].handler_function)
2297 if (pcnt>=cmdlist[i].min_params)
2299 if (strchr(user->modes,cmdlist[i].flags_needed))
2301 cmdlist[i].handler_function(parameters,pcnt,user);
2309 void DoSplitEveryone()
2311 bool go_again = true;
2315 for (int i = 0; i < 32; i++)
2319 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2321 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2324 j->CloseConnection();
2325 me[i]->connectors.erase(j);
2333 log(DEBUG,"Removed server. Will remove clients...");
2334 // iterate through the userlist and remove all users on this server.
2335 // because we're dealing with a mesh, we dont have to deal with anything
2336 // "down-route" from this server (nice huh)
2338 char reason[MAXBUF];
2342 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2344 if (strcasecmp(u->second->server,ServerName))
2346 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2347 kill_link(u->second,reason);
2357 char islast(const char* s)
2360 for (int j = 0; j < 32; j++)
2364 for (int k = 0; k < me[j]->connectors.size(); k++)
2366 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2370 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2380 long map_count(const char* s)
2383 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2385 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2391 void force_nickchange(userrec* user,const char* newnick)
2398 FOREACH_RESULT(OnUserPreNick(user,newnick));
2400 kill_link(user,"Nickname collision");
2403 if (matches_qline(newnick))
2405 kill_link(user,"Nickname collision");
2413 strncpy(nick,newnick,MAXBUF);
2415 if (user->registered == 7)
2419 handle_nick(pars,1,user);
2425 int process_parameters(char **command_p,char *parameters)
2430 q = strlen(parameters);
2433 /* no parameters, command_p invalid! */
2436 if (parameters[0] == ':')
2438 command_p[0] = parameters+1;
2443 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2445 /* only one parameter */
2446 command_p[0] = parameters;
2447 if (parameters[0] == ':')
2449 if (strchr(parameters,' ') != NULL)
2457 command_p[j++] = parameters;
2458 for (int i = 0; i <= q; i++)
2460 if (parameters[i] == ' ')
2462 command_p[j++] = parameters+i+1;
2463 parameters[i] = '\0';
2464 if (command_p[j-1][0] == ':')
2466 *command_p[j-1]++; /* remove dodgy ":" */
2468 /* parameter like this marks end of the sequence */
2472 return j; /* returns total number of items in the list */
2475 void process_command(userrec *user, char* cmd)
2479 char *command_p[127];
2480 char p[MAXBUF], temp[MAXBUF];
2481 int i, j, items, cmd_found;
2483 for (int i = 0; i < 127; i++)
2484 command_p[i] = NULL;
2494 if (!strcmp(cmd,""))
2499 int total_params = 0;
2502 for (int q = 0; q < strlen(cmd)-1; q++)
2504 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2507 // found a 'trailing', we dont count them after this.
2515 // another phidjit bug...
2516 if (total_params > 126)
2518 kill_link(user,"Protocol violation (1)");
2524 std::string tmp = cmd;
2525 for (int i = 0; i <= MODCOUNT; i++)
2527 std::string oldtmp = tmp;
2528 modules[i]->OnServerRaw(tmp,true);
2531 log(DEBUG,"A Module changed the input string!");
2532 log(DEBUG,"New string: %s",tmp.c_str());
2533 log(DEBUG,"Old string: %s",oldtmp.c_str());
2537 strncpy(cmd,tmp.c_str(),MAXBUF);
2540 if (!strchr(cmd,' '))
2542 /* no parameters, lets skip the formalities and not chop up
2544 log(DEBUG,"About to preprocess command with no params");
2546 command_p[0] = NULL;
2548 for (int i = 0; i <= strlen(cmd); i++)
2550 cmd[i] = toupper(cmd[i]);
2552 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2559 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2560 for (int i = 0; i < strlen(temp); i++)
2562 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2568 /* split the full string into a command plus parameters */
2572 if (strchr(cmd,' '))
2574 for (int i = 0; i <= strlen(cmd); i++)
2576 /* capitalise the command ONLY, leave params intact */
2577 cmd[i] = toupper(cmd[i]);
2578 /* are we nearly there yet?! :P */
2582 parameters = cmd+i+1;
2590 for (int i = 0; i <= strlen(cmd); i++)
2592 cmd[i] = toupper(cmd[i]);
2599 if (strlen(command)>MAXCOMMAND)
2601 kill_link(user,"Protocol violation (2)");
2605 for (int x = 0; x < strlen(command); x++)
2607 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2609 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2611 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2613 kill_link(user,"Protocol violation (3)");
2620 for (int i = 0; i != cmdlist.size(); i++)
2622 if (strcmp(cmdlist[i].command,""))
2624 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2626 log(DEBUG,"Found matching command");
2630 if (strcmp(parameters,""))
2632 items = process_parameters(command_p,parameters);
2637 command_p[0] = NULL;
2643 command_p[0] = NULL;
2648 log(DEBUG,"Processing command");
2650 /* activity resets the ping pending timer */
2651 user->nping = time(NULL) + 120;
2652 if ((items) < cmdlist[i].min_params)
2654 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2655 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2658 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2660 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2661 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2665 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2667 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2669 if ((!isnick(user->nick)) || (user->registered != 7))
2671 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2672 WriteServ(user->fd,"451 %s :You have not registered",command);
2676 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2678 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2679 if (cmdlist[i].handler_function)
2681 /* ikky /stats counters */
2686 user->bytes_in += strlen(temp);
2689 cmdlist[i].use_count++;
2690 cmdlist[i].total_bytes+=strlen(temp);
2693 /* WARNING: nothing may come after the
2694 * command handler call, as the handler
2695 * may free the user structure! */
2697 cmdlist[i].handler_function(command_p,items,user);
2703 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2704 WriteServ(user->fd,"451 %s :You have not registered",command);
2712 if ((!cmd_found) && (user))
2714 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2715 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2720 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2723 /* create the command and push it onto the table */
2724 strcpy(comm.command,cmd);
2725 comm.handler_function = f;
2726 comm.flags_needed = flags;
2727 comm.min_params = minparams;
2729 comm.total_bytes = 0;
2730 cmdlist.push_back(comm);
2731 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2734 void SetupCommandTable(void)
2736 createcommand("USER",handle_user,0,4);
2737 createcommand("NICK",handle_nick,0,1);
2738 createcommand("QUIT",handle_quit,0,0);
2739 createcommand("VERSION",handle_version,0,0);
2740 createcommand("PING",handle_ping,0,1);
2741 createcommand("PONG",handle_pong,0,1);
2742 createcommand("ADMIN",handle_admin,0,0);
2743 createcommand("PRIVMSG",handle_privmsg,0,2);
2744 createcommand("INFO",handle_info,0,0);
2745 createcommand("TIME",handle_time,0,0);
2746 createcommand("WHOIS",handle_whois,0,1);
2747 createcommand("WALLOPS",handle_wallops,'o',1);
2748 createcommand("NOTICE",handle_notice,0,2);
2749 createcommand("JOIN",handle_join,0,1);
2750 createcommand("NAMES",handle_names,0,1);
2751 createcommand("PART",handle_part,0,1);
2752 createcommand("KICK",handle_kick,0,2);
2753 createcommand("MODE",handle_mode,0,1);
2754 createcommand("TOPIC",handle_topic,0,1);
2755 createcommand("WHO",handle_who,0,1);
2756 createcommand("MOTD",handle_motd,0,0);
2757 createcommand("RULES",handle_rules,0,0);
2758 createcommand("OPER",handle_oper,0,2);
2759 createcommand("LIST",handle_list,0,0);
2760 createcommand("DIE",handle_die,'o',1);
2761 createcommand("RESTART",handle_restart,'o',1);
2762 createcommand("KILL",handle_kill,'o',2);
2763 createcommand("REHASH",handle_rehash,'o',0);
2764 createcommand("LUSERS",handle_lusers,0,0);
2765 createcommand("STATS",handle_stats,0,1);
2766 createcommand("USERHOST",handle_userhost,0,1);
2767 createcommand("AWAY",handle_away,0,0);
2768 createcommand("ISON",handle_ison,0,0);
2769 createcommand("SUMMON",handle_summon,0,0);
2770 createcommand("USERS",handle_users,0,0);
2771 createcommand("INVITE",handle_invite,0,2);
2772 createcommand("PASS",handle_pass,0,1);
2773 createcommand("TRACE",handle_trace,'o',0);
2774 createcommand("WHOWAS",handle_whowas,0,1);
2775 createcommand("CONNECT",handle_connect,'o',1);
2776 createcommand("SQUIT",handle_squit,'o',0);
2777 createcommand("MODULES",handle_modules,'o',0);
2778 createcommand("LINKS",handle_links,0,0);
2779 createcommand("MAP",handle_map,0,0);
2780 createcommand("KLINE",handle_kline,'o',1);
2781 createcommand("GLINE",handle_gline,'o',1);
2782 createcommand("ZLINE",handle_zline,'o',1);
2783 createcommand("QLINE",handle_qline,'o',1);
2786 void process_buffer(const char* cmdbuf,userrec *user)
2790 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2797 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2800 if (!strcmp(cmdbuf,""))
2804 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2806 strncpy(cmd,cmdbuf,MAXBUF);
2807 if (!strcmp(cmd,""))
2811 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2813 cmd[strlen(cmd)-1] = '\0';
2815 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2817 cmd[strlen(cmd)-1] = '\0';
2820 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2822 cmd[strlen(cmd)-1] = '\0';
2825 if (!strcmp(cmd,""))
2829 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2831 if ((user) && (cmd))
2833 process_command(user,cmd);
2837 void DoSync(serverrec* serv, char* tcp_host)
2840 log(DEBUG,"Sending sync");
2841 // send start of sync marker: Y <timestamp>
2842 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2843 // except the ones its receiving it from.
2844 snprintf(data,MAXBUF,"Y %d",time(NULL));
2845 serv->SendPacket(data,tcp_host);
2846 // send users and channels
2847 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2849 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);
2850 serv->SendPacket(data,tcp_host);
2851 if (strcmp(chlist(u->second),""))
2853 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2854 serv->SendPacket(data,tcp_host);
2857 // send channel modes, topics etc...
2858 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2860 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2861 serv->SendPacket(data,tcp_host);
2862 if (strcmp(c->second->topic,""))
2864 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2865 serv->SendPacket(data,tcp_host);
2867 // send current banlist
2869 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2871 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2872 serv->SendPacket(data,tcp_host);
2875 snprintf(data,MAXBUF,"F %d",time(NULL));
2876 serv->SendPacket(data,tcp_host);
2877 log(DEBUG,"Sent sync");
2878 // ircd sends its serverlist after the end of sync here
2882 void NetSendMyRoutingTable()
2884 // send out a line saying what is reachable to us.
2885 // E.g. if A is linked to B C and D, send out:
2887 // if its only linked to B and D send out:
2889 // if it has no links, dont even send out the line at all.
2890 char buffer[MAXBUF];
2891 sprintf(buffer,"$ %s",ServerName);
2892 bool sendit = false;
2893 for (int i = 0; i < 32; i++)
2897 for (int j = 0; j < me[i]->connectors.size(); j++)
2899 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2901 strncat(buffer," ",MAXBUF);
2902 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2909 NetSendToAll(buffer);
2913 void DoSplit(const char* params)
2915 bool go_again = true;
2919 for (int i = 0; i < 32; i++)
2923 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2925 if (!strcasecmp(j->GetServerName().c_str(),params))
2928 j->CloseConnection();
2929 me[i]->connectors.erase(j);
2937 log(DEBUG,"Removed server. Will remove clients...");
2938 // iterate through the userlist and remove all users on this server.
2939 // because we're dealing with a mesh, we dont have to deal with anything
2940 // "down-route" from this server (nice huh)
2942 char reason[MAXBUF];
2943 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2947 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2949 if (!strcasecmp(u->second->server,params))
2951 kill_link(u->second,reason);
2959 // removes a server. Will NOT remove its users!
2961 void RemoveServer(const char* name)
2963 bool go_again = true;
2967 for (int i = 0; i < 32; i++)
2971 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2973 if (!strcasecmp(j->GetServerName().c_str(),name))
2976 j->CloseConnection();
2977 me[i]->connectors.erase(j);
2988 int reap_counter = 0;
2992 struct sockaddr_in client, server;
2993 char addrs[MAXBUF][255];
2994 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
2996 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
2997 int selectResult = 0, selectResult2 = 0;
2998 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2999 char resolvedHost[MAXBUF];
3003 log_file = fopen("ircd.log","a+");
3006 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3010 log(DEBUG,"InspIRCd: startup: begin");
3014 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3016 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3018 SetupCommandTable();
3019 log(DEBUG,"InspIRCd: startup: default command table set up");
3022 if (strcmp(DieValue,""))
3024 printf("WARNING: %s\n\n",DieValue);
3027 log(DEBUG,"InspIRCd: startup: read config");
3029 int count2 = 0, count3 = 0;
3031 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3033 ConfValue("bind","port",count,configToken,&config_f);
3034 ConfValue("bind","address",count,Addr,&config_f);
3035 ConfValue("bind","type",count,Type,&config_f);
3036 if (!strcmp(Type,"servers"))
3038 char Default[MAXBUF];
3039 strcpy(Default,"no");
3040 ConfValue("bind","default",count,Default,&config_f);
3041 if (strchr(Default,'y'))
3043 defaultRoute = count3;
3044 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3046 me[count3] = new serverrec(ServerName,100L,false);
3047 me[count3]->CreateListener(Addr,atoi(configToken));
3052 ports[count2] = atoi(configToken);
3053 strcpy(addrs[count2],Addr);
3056 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3059 UDPportCount = count3;
3061 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3063 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3067 /* BugFix By Craig! :p */
3069 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3071 char modfile[MAXBUF];
3072 ConfValue("module","name",count2,configToken,&config_f);
3073 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3074 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3075 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3076 /* If The File Doesnt exist, Trying to load it
3077 * Will Segfault the IRCd.. So, check to see if
3078 * it Exists, Before Proceeding. */
3079 if (FileExists(modfile))
3081 factory[count] = new ircd_module(modfile);
3082 if (factory[count]->LastError())
3084 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3085 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3088 if (factory[count]->factory)
3090 modules[count] = factory[count]->factory->CreateModule();
3091 /* save the module and the module's classfactory, if
3092 * this isnt done, random crashes can occur :/ */
3093 module_names.push_back(modfile);
3097 log(DEBUG,"Unable to load %s",modfile);
3098 sprintf("Unable to load %s\nExiting...\n",modfile);
3101 /* Increase the Count */
3106 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3107 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3110 MODCOUNT = count - 1;
3111 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3113 printf("\nInspIRCd is now running!\n");
3115 startup_time = time(NULL);
3119 log(VERBOSE,"Not forking as -nofork was specified");
3123 if (DaemonSeed() == ERROR)
3125 log(DEBUG,"InspIRCd: startup: can't daemonise");
3126 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3132 /* setup select call */
3133 FD_ZERO(&selectFds);
3134 log(DEBUG,"InspIRCd: startup: zero selects");
3135 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3137 for (count = 0; count < portCount; count++)
3139 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3141 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3144 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3146 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3148 else /* well we at least bound to one socket so we'll continue */
3154 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3156 /* if we didn't bind to anything then abort */
3157 if (boundPortCount == 0)
3159 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3164 length = sizeof (client);
3165 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3167 /* main loop, this never returns */
3170 #ifdef _POSIX_PRIORITY_SCHEDULING
3173 // update the status of klines, etc
3180 user_hash::iterator count2 = clientlist.begin();
3182 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3183 // them in a list, then reap the list every second or so.
3184 if (reap_counter>300)
3186 if (fd_reap.size() > 0)
3188 for( int n = 0; n < fd_reap.size(); n++)
3190 Blocking(fd_reap[n]);
3192 NonBlocking(fd_reap[n]);
3201 FD_ZERO(&serverfds);
3204 for (int x = 0; x != UDPportCount; x++)
3206 FD_SET(me[x]->fd, &serverfds);
3212 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3215 for (int x = 0; x != UDPportCount; x++)
3217 if (FD_ISSET (me[x]->fd, &serverfds))
3219 char remotehost[MAXBUF],resolved[MAXBUF];
3220 length = sizeof (client);
3221 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3222 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3223 if(CleanAndResolve(resolved, remotehost) != TRUE)
3225 strncpy(resolved,remotehost,MAXBUF);
3227 // add to this connections ircd_connector vector
3228 // *FIX* - we need the LOCAL port not the remote port in &client!
3229 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3234 for (int x = 0; x < UDPportCount; x++)
3236 std::deque<std::string> msgs;
3238 if (me[x]->RecvPacket(msgs, tcp_host))
3240 for (int ctr = 0; ctr < msgs.size(); ctr++)
3242 char udp_msg[MAXBUF];
3243 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3244 if (strlen(udp_msg)<1)
3246 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3249 // during a netburst, send all data to all other linked servers
3250 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3252 if (is_uline(tcp_host))
3254 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3256 NetSendToAllExcept(tcp_host,udp_msg);
3260 NetSendToAllExcept(tcp_host,udp_msg);
3262 FOREACH_MOD OnPacketReceive(udp_msg);
3263 handle_link_packet(udp_msg, tcp_host, me[x]);
3270 while (count2 != clientlist.end())
3273 tval.tv_usec = tval.tv_sec = 0;
3275 int total_in_this_set = 0;
3277 user_hash::iterator xcount = count2;
3278 user_hash::iterator endingiter = count2;
3280 if (!count2->second) break;
3283 if (count2->second->fd != 0)
3285 // assemble up to 64 sockets into an fd_set
3286 // to implement a pooling mechanism.
3288 // This should be up to 64x faster than the
3289 // old implementation.
3290 while (total_in_this_set < 64)
3292 if (count2 != clientlist.end())
3294 // we don't check the state of remote users.
3295 if (count2->second->fd > 0)
3297 FD_SET (count2->second->fd, &sfd);
3299 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3300 // their connection class.
3301 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3303 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3304 kill_link(count2->second,"Registration timeout");
3307 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3309 if ((!count2->second->lastping) && (count2->second->registered == 7))
3311 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3312 kill_link(count2->second,"Ping timeout");
3315 Write(count2->second->fd,"PING :%s",ServerName);
3316 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3317 count2->second->lastping = 0;
3318 count2->second->nping = time(NULL)+120;
3322 total_in_this_set++;
3327 endingiter = count2;
3328 count2 = xcount; // roll back to where we were
3334 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3336 // now loop through all of the items in this pool if any are waiting
3337 //if (selectResult2 > 0)
3338 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3341 #ifdef _POSIX_PRIORITY_SCHEDULING
3346 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3348 log(DEBUG,"Reading fd %d",count2a->second->fd);
3349 memset(data, 0, 10240);
3350 result = read(count2a->second->fd, data, 10240);
3355 log(DEBUG,"Read %d characters from socket",result);
3356 userrec* current = count2a->second;
3357 int currfd = current->fd;
3358 char* l = strtok(data,"\n");
3363 if ((floodlines > current->flood) && (current->flood != 0))
3365 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3366 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3367 kill_link(current,"Excess flood");
3370 char sanitized[NetBufferSize];
3371 memset(sanitized, 0, NetBufferSize);
3373 for (int pt = 0; pt < strlen(l); pt++)
3377 sanitized[ptt++] = l[pt];
3380 sanitized[ptt] = '\0';
3381 if (strlen(sanitized))
3385 // we're gonna re-scan to check if the nick is gone, after every
3386 // command - if it has, we're gonna bail
3387 bool find_again = false;
3388 process_buffer(sanitized,current);
3390 // look for the user's record in case it's changed
3391 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3393 if (c2->second->fd == currfd)
3395 // found again, update pointer
3396 current == c2->second;
3405 l = strtok(NULL,"\n");
3410 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3412 log(DEBUG,"killing: %s",count2a->second->nick);
3413 kill_link(count2a->second,strerror(errno));
3417 // result EAGAIN means nothing read
3418 if (result == EAGAIN)
3426 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3427 kill_link(count2a->second,"Client exited");
3428 // must bail here? kill_link removes the hash, corrupting the iterator
3429 log(DEBUG,"Bailing from client exit");
3433 else if (result > 0)
3438 for (int q = 0; q < total_in_this_set; q++)
3440 // there is no iterator += operator :(
3441 //if (count2 != clientlist.end())
3448 // set up select call
3449 for (count = 0; count < boundPortCount; count++)
3451 FD_SET (openSockfd[count], &selectFds);
3455 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3457 /* select is reporting a waiting socket. Poll them all to find out which */
3458 if (selectResult > 0)
3460 char target[MAXBUF], resolved[MAXBUF];
3461 for (count = 0; count < boundPortCount; count++)
3463 if (FD_ISSET (openSockfd[count], &selectFds))
3465 length = sizeof (client);
3466 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3468 address_cache::iterator iter = IP.find(client.sin_addr);
3469 bool iscached = false;
3470 if (iter == IP.end())
3472 /* ip isn't in cache, add it */
3473 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3474 if(CleanAndResolve(resolved, target) != TRUE)
3476 strncpy(resolved,target,MAXBUF);
3478 /* hostname now in 'target' */
3479 IP[client.sin_addr] = new string(resolved);
3480 /* hostname in cache */
3484 /* found ip (cached) */
3485 strncpy(resolved, iter->second->c_str(), MAXBUF);
3489 if (incomingSockfd < 0)
3491 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3492 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3496 AddClient(incomingSockfd, resolved, ports[count], iscached, target);
3497 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3504 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3507 close (incomingSockfd);