1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
46 #include "connection.h"
58 #define nspace __gnu_cxx
63 int LogLevel = DEFAULT;
64 char ServerName[MAXBUF];
66 char ServerDesc[MAXBUF];
67 char AdminName[MAXBUF];
68 char AdminEmail[MAXBUF];
69 char AdminNick[MAXBUF];
71 char restartpass[MAXBUF];
75 char PrefixQuit[MAXBUF];
76 char DieValue[MAXBUF];
78 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
79 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
81 time_t startup_time = time(NULL);
82 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
85 extern vector<Module*> modules;
86 std::vector<std::string> module_names;
87 extern vector<ircd_module*> factory;
88 std::vector<int> fd_reap;
96 template<> struct nspace::hash<in_addr>
98 size_t operator()(const struct in_addr &a) const
101 memcpy(&q,&a,sizeof(size_t));
106 template<> struct nspace::hash<string>
108 size_t operator()(const string &s) const
111 static struct hash<const char *> strhash;
123 bool operator()(const string& s1, const string& s2) const
125 char a[MAXBUF],b[MAXBUF];
126 strcpy(a,s1.c_str());
127 strcpy(b,s2.c_str());
128 return (strcasecmp(a,b) == 0);
133 struct InAddr_HashComp
136 bool operator()(const in_addr &s1, const in_addr &s2) const
141 memcpy(&q,&s1,sizeof(size_t));
142 memcpy(&p,&s2,sizeof(size_t));
150 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
151 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
152 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
153 typedef std::deque<command_t> command_table;
159 user_hash clientlist;
162 command_table cmdlist;
169 struct linger linger = { 0 };
170 char bannerBuffer[MAXBUF];
171 int boundPortCount = 0;
172 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
173 int defaultRoute = 0;
177 long MyKey = C.GenKey();
181 int has_channel(userrec *u, chanrec *c);
182 int usercount(chanrec *c);
183 int usercount_i(chanrec *c);
184 void update_stats_l(int fd,int data_out);
185 char* Passwd(userrec *user);
186 bool IsDenied(userrec *user);
187 void AddWhoWas(userrec* u);
189 std::vector<long> auth_cookies;
190 std::stringstream config_f(stringstream::in | stringstream::out);
196 char Revision[] = "$Revision$";
199 char *v1 = strtok_r(s1," ",&savept);
201 char *v2 = strtok_r(s1," ",&savept);
203 return (long)(atof(v2)*10000);
207 std::string getservername()
212 std::string getserverdesc()
217 std::string getnetworkname()
222 std::string getadminname()
227 std::string getadminemail()
232 std::string getadminnick()
237 void log(int level,char *text, ...)
239 char textbuffer[MAXBUF];
242 struct tm * timeinfo;
243 if (level < LogLevel)
247 timeinfo = localtime (&rawtime);
252 va_start (argsPtr, text);
253 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
255 strcpy(b,asctime(timeinfo));
256 b[strlen(b)-1] = ':';
257 fprintf(log_file,"%s %s\n",b,textbuffer);
260 // nofork enabled? display it on terminal too
261 printf("%s %s\n",b,textbuffer);
266 void readfile(file_cache &F, const char* fname)
269 char linebuf[MAXBUF];
271 log(DEBUG,"readfile: loading %s",fname);
273 file = fopen(fname,"r");
278 fgets(linebuf,sizeof(linebuf),file);
279 linebuf[strlen(linebuf)-1]='\0';
280 if (!strcmp(linebuf,""))
286 F.push_back(linebuf);
293 log(DEBUG,"readfile: failed to load file: %s",fname);
295 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
298 void ReadConfig(void)
300 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
303 LoadConf(CONFIG_FILE,&config_f);
305 ConfValue("server","name",0,ServerName,&config_f);
306 ConfValue("server","description",0,ServerDesc,&config_f);
307 ConfValue("server","network",0,Network,&config_f);
308 ConfValue("admin","name",0,AdminName,&config_f);
309 ConfValue("admin","email",0,AdminEmail,&config_f);
310 ConfValue("admin","nick",0,AdminNick,&config_f);
311 ConfValue("files","motd",0,motd,&config_f);
312 ConfValue("files","rules",0,rules,&config_f);
313 ConfValue("power","diepass",0,diepass,&config_f);
314 ConfValue("power","pause",0,pauseval,&config_f);
315 ConfValue("power","restartpass",0,restartpass,&config_f);
316 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
317 ConfValue("die","value",0,DieValue,&config_f);
318 ConfValue("options","loglevel",0,dbg,&config_f);
319 ConfValue("options","netbuffersize",0,NB,&config_f);
320 NetBufferSize = atoi(NB);
321 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
323 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
324 NetBufferSize = 10240;
326 if (!strcmp(dbg,"debug"))
328 if (!strcmp(dbg,"verbose"))
330 if (!strcmp(dbg,"default"))
332 if (!strcmp(dbg,"sparse"))
334 if (!strcmp(dbg,"none"))
337 log(DEBUG,"Reading message of the day");
338 readfile(RULES,rules);
339 log(DEBUG,"Reading connect classes");
341 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
344 ConfValue("connect","allow",i,Value,&config_f);
345 ConfValue("connect","timeout",i,timeout,&config_f);
346 ConfValue("connect","flood",i,flood,&config_f);
347 if (strcmp(Value,""))
349 strcpy(c.host,Value);
352 ConfValue("connect","password",i,Value,&config_f);
353 strcpy(c.pass,Value);
354 c.registration_timeout = 90; // default is 2 minutes
355 c.flood = atoi(flood);
358 c.registration_timeout = atoi(timeout);
360 Classes.push_back(c);
361 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
365 ConfValue("connect","deny",i,Value,&config_f);
366 strcpy(c.host,Value);
368 Classes.push_back(c);
369 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
375 /* write formatted text to a socket, in same format as printf */
377 void Write(int sock,char *text, ...)
381 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
384 char textbuffer[MAXBUF];
388 va_start (argsPtr, text);
389 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
391 sprintf(tb,"%s\r\n",textbuffer);
395 write(sock,tb,strlen(tb));
396 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
400 /* write a server formatted numeric response to a single socket */
402 void WriteServ(int sock, char* text, ...)
406 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
409 char textbuffer[MAXBUF],tb[MAXBUF];
411 va_start (argsPtr, text);
413 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
415 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
419 write(sock,tb,strlen(tb));
420 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
424 /* write text from an originating user to originating user */
426 void WriteFrom(int sock, userrec *user,char* text, ...)
428 if ((!text) || (!user))
430 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
433 char textbuffer[MAXBUF],tb[MAXBUF];
435 va_start (argsPtr, text);
437 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
439 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
443 write(sock,tb,strlen(tb));
444 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
448 /* write text to an destination user from a source user (e.g. user privmsg) */
450 void WriteTo(userrec *source, userrec *dest,char *data, ...)
452 if ((!dest) || (!data))
454 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
457 char textbuffer[MAXBUF],tb[MAXBUF];
459 va_start (argsPtr, data);
460 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
464 // if no source given send it from the server.
467 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
471 WriteFrom(dest->fd,source,"%s",textbuffer);
475 /* write formatted text from a source user to all users on a channel
476 * including the sender (NOT for privmsg, notice etc!) */
478 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
480 if ((!Ptr) || (!user) || (!text))
482 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
485 char textbuffer[MAXBUF];
487 va_start (argsPtr, text);
488 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
490 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
492 if (has_channel(i->second,Ptr))
494 WriteTo(user,i->second,"%s",textbuffer);
499 /* write formatted text from a source user to all users on a channel
500 * including the sender (NOT for privmsg, notice etc!) doesnt send to
501 * users on remote servers */
503 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
505 if ((!Ptr) || (!text))
507 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
510 char textbuffer[MAXBUF];
512 va_start (argsPtr, text);
513 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
515 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
517 if (has_channel(i->second,Ptr))
519 if (i->second->fd != -1)
523 WriteServ(i->second->fd,"%s",textbuffer);
527 WriteTo(user,i->second,"%s",textbuffer);
535 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
537 if ((!Ptr) || (!user) || (!text))
539 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
542 char textbuffer[MAXBUF];
544 va_start (argsPtr, text);
545 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
547 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
551 if (has_channel(i->second,Ptr))
553 WriteServ(i->second->fd,"%s",textbuffer);
560 /* write formatted text from a source user to all users on a channel except
561 * for the sender (for privmsg etc) */
563 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
565 if ((!Ptr) || (!user) || (!text))
567 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
570 char textbuffer[MAXBUF];
572 va_start (argsPtr, text);
573 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
576 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
580 if (has_channel(i->second,Ptr) && (user != i->second))
582 WriteTo(user,i->second,"%s",textbuffer);
589 std::string GetServerDescription(char* servername)
591 for (int j = 0; j < 32; j++)
595 for (int k = 0; k < me[j]->connectors.size(); k++)
597 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
599 return me[j]->connectors[k].GetDescription();
603 return ServerDesc; // not a remote server that can be found, it must be me.
608 /* write a formatted string to all users who share at least one common
609 * channel, including the source user e.g. for use in NICK */
611 void WriteCommon(userrec *u, char* text, ...)
615 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
619 if (u->registered != 7) {
620 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
624 char textbuffer[MAXBUF];
626 va_start (argsPtr, text);
627 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
630 WriteFrom(u->fd,u,"%s",textbuffer);
632 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
636 if (common_channels(u,i->second) && (i->second != u))
638 WriteFrom(i->second->fd,u,"%s",textbuffer);
644 /* write a formatted string to all users who share at least one common
645 * channel, NOT including the source user e.g. for use in QUIT */
647 void WriteCommonExcept(userrec *u, char* text, ...)
651 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
655 if (u->registered != 7) {
656 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
660 char textbuffer[MAXBUF];
662 va_start (argsPtr, text);
663 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
666 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
670 if ((common_channels(u,i->second)) && (u != i->second))
672 WriteFrom(i->second->fd,u,"%s",textbuffer);
678 void WriteOpers(char* text, ...)
682 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
686 char textbuffer[MAXBUF];
688 va_start (argsPtr, text);
689 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
692 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
696 if (strchr(i->second->modes,'o'))
698 if (strchr(i->second->modes,'s'))
700 // send server notices to all with +s
701 // (TODO: needs SNOMASKs)
702 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
709 // returns TRUE of any users on channel C occupy server 'servername'.
711 bool ChanAnyOnThisServer(chanrec *c,char* servername)
713 log(DEBUG,"ChanAnyOnThisServer");
714 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
716 if (has_channel(i->second,c))
718 if (!strcasecmp(i->second->server,servername))
727 // returns true if user 'u' shares any common channels with any users on server 'servername'
729 bool CommonOnThisServer(userrec* u,const char* servername)
731 log(DEBUG,"ChanAnyOnThisServer");
732 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
734 if ((common_channels(u,i->second)) && (u != i->second))
736 if (!strcasecmp(i->second->server,servername))
738 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
747 void NetSendToCommon(userrec* u, char* s)
750 snprintf(buffer,MAXBUF,"%s",s);
752 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
754 for (int j = 0; j < 32; j++)
758 for (int k = 0; k < me[j]->connectors.size(); k++)
760 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
762 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
770 void NetSendToAll(char* s)
773 snprintf(buffer,MAXBUF,"%s",s);
775 log(DEBUG,"NetSendToAll: '%s'",s);
777 for (int j = 0; j < 32; j++)
781 for (int k = 0; k < me[j]->connectors.size(); k++)
783 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
789 void NetSendToAllAlive(char* s)
792 snprintf(buffer,MAXBUF,"%s",s);
794 log(DEBUG,"NetSendToAllAlive: '%s'",s);
796 for (int j = 0; j < 32; j++)
800 for (int k = 0; k < me[j]->connectors.size(); k++)
802 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
804 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
808 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
816 void NetSendToOne(char* target,char* s)
819 snprintf(buffer,MAXBUF,"%s",s);
821 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
823 for (int j = 0; j < 32; j++)
827 for (int k = 0; k < me[j]->connectors.size(); k++)
829 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
831 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
838 void NetSendToAllExcept(const char* target,char* s)
841 snprintf(buffer,MAXBUF,"%s",s);
843 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
845 for (int j = 0; j < 32; j++)
849 for (int k = 0; k < me[j]->connectors.size(); k++)
851 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
853 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
861 void WriteMode(const char* modes, int flags, const char* text, ...)
863 if ((!text) || (!modes) || (!flags))
865 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
869 char textbuffer[MAXBUF];
871 va_start (argsPtr, text);
872 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
875 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
879 bool send_to_user = false;
884 for (int n = 0; n < strlen(modes); n++)
886 if (!hasumode(i->second,modes[n]))
888 send_to_user = false;
893 else if (flags == WM_OR)
895 send_to_user = false;
896 for (int n = 0; n < strlen(modes); n++)
898 if (hasumode(i->second,modes[n]))
908 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
915 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
917 if ((!text) || (!source))
919 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
924 char textbuffer[MAXBUF];
926 va_start (argsPtr, text);
927 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
930 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
934 if (strchr(i->second->modes,'w'))
936 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
944 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
945 NetSendToAll(buffer);
949 /* convert a string to lowercase. Note following special circumstances
950 * taken from RFC 1459. Many "official" server branches still hold to this
951 * rule so i will too;
953 * Because of IRC's scandanavian origin, the characters {}| are
954 * considered to be the lower case equivalents of the characters []\,
955 * respectively. This is a critical issue when determining the
956 * equivalence of two nicknames.
959 void strlower(char *n)
965 for (int i = 0; i != strlen(n); i++)
967 n[i] = tolower(n[i]);
979 /* Find a user record by nickname and return a pointer to it */
981 userrec* Find(string nick)
983 user_hash::iterator iter = clientlist.find(nick);
985 if (iter == clientlist.end())
986 /* Couldn't find it */
992 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
994 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
998 if (i->second->fd == fd)
1000 i->second->bytes_out+=data_out;
1001 i->second->cmds_out++;
1008 /* find a channel record by channel name and return a pointer to it */
1010 chanrec* FindChan(const char* chan)
1014 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1018 chan_hash::iterator iter = chanlist.find(chan);
1020 if (iter == chanlist.end())
1021 /* Couldn't find it */
1024 return iter->second;
1028 void purge_empty_chans(void)
1030 int go_again = 1, purge = 0;
1035 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1038 if (!usercount(i->second))
1040 /* kill the record */
1041 if (i != chanlist.end())
1043 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1053 log(DEBUG,"skipped purge for %s",i->second->name);
1058 log(DEBUG,"completed channel purge, killed %d",purge);
1062 char scratch[MAXBUF];
1063 char sparam[MAXBUF];
1065 char* chanmodes(chanrec *chan)
1069 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1076 if (chan->noexternal)
1078 strncat(scratch,"n",MAXMODES);
1080 if (chan->topiclock)
1082 strncat(scratch,"t",MAXMODES);
1084 if (strcmp(chan->key,""))
1086 strncat(scratch,"k",MAXMODES);
1090 strncat(scratch,"l",MAXMODES);
1092 if (chan->inviteonly)
1094 strncat(scratch,"i",MAXMODES);
1096 if (chan->moderated)
1098 strncat(scratch,"m",MAXMODES);
1102 strncat(scratch,"s",MAXMODES);
1104 if (chan->c_private)
1106 strncat(scratch,"p",MAXMODES);
1108 if (strcmp(chan->key,""))
1110 strncat(sparam,chan->key,MAXBUF);
1115 sprintf(foo," %d",chan->limit);
1116 strncat(sparam,foo,MAXBUF);
1118 if (strlen(chan->custom_modes))
1120 strncat(scratch,chan->custom_modes,MAXMODES);
1121 for (int z = 0; z < strlen(chan->custom_modes); z++)
1123 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1126 strncat(sparam," ",MAXBUF);
1127 strncat(sparam,extparam.c_str(),MAXBUF);
1131 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1132 strncat(scratch,sparam,MAXMODES);
1137 /* compile a userlist of a channel into a string, each nick seperated by
1138 * spaces and op, voice etc status shown as @ and + */
1140 void userlist(userrec *user,chanrec *c)
1142 if ((!c) || (!user))
1144 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1148 sprintf(list,"353 %s = %s :", user->nick, c->name);
1149 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1151 if (has_channel(i->second,c))
1153 if (isnick(i->second->nick))
1155 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1157 /* user is +i, and source not on the channel, does not show
1158 * nick in NAMES list */
1161 strcat(list,cmode(i->second,c));
1162 strcat(list,i->second->nick);
1164 if (strlen(list)>(480-NICKMAX))
1166 /* list overflowed into
1167 * multiple numerics */
1168 WriteServ(user->fd,list);
1169 sprintf(list,"353 %s = %s :", user->nick, c->name);
1174 /* if whats left in the list isnt empty, send it */
1175 if (list[strlen(list)-1] != ':')
1177 WriteServ(user->fd,list);
1181 /* return a count of the users on a specific channel accounting for
1182 * invisible users who won't increase the count. e.g. for /LIST */
1184 int usercount_i(chanrec *c)
1191 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1196 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1200 if (has_channel(i->second,c))
1202 if (isnick(i->second->nick))
1204 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1206 /* user is +i, and source not on the channel, does not show
1207 * nick in NAMES list */
1215 log(DEBUG,"usercount_i: %s %d",c->name,count);
1220 int usercount(chanrec *c)
1227 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1232 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1236 if (has_channel(i->second,c))
1238 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1245 log(DEBUG,"usercount: %s %d",c->name,count);
1250 /* add a channel to a user, creating the record for it if needed and linking
1251 * it to the user record */
1253 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1255 if ((!user) || (!cn))
1257 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1266 strncpy(cname,cn,MAXBUF);
1268 // we MUST declare this wherever we use FOREACH_RESULT
1271 if (strlen(cname) > CHANMAX-1)
1273 cname[CHANMAX-1] = '\0';
1276 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1278 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1280 return NULL; // already on the channel!
1284 if (!FindChan(cname))
1286 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1291 /* create a new one */
1292 log(DEBUG,"add_channel: creating: %s",cname);
1294 chanlist[cname] = new chanrec();
1296 strcpy(chanlist[cname]->name, cname);
1297 chanlist[cname]->topiclock = 1;
1298 chanlist[cname]->noexternal = 1;
1299 chanlist[cname]->created = time(NULL);
1300 strcpy(chanlist[cname]->topic, "");
1301 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1302 chanlist[cname]->topicset = 0;
1303 Ptr = chanlist[cname];
1304 log(DEBUG,"add_channel: created: %s",cname);
1305 /* set created to 2 to indicate user
1306 * is the first in the channel
1307 * and should be given ops */
1313 /* channel exists, just fish out a pointer to its struct */
1314 Ptr = FindChan(cname);
1317 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1319 // the override flag allows us to bypass channel modes
1320 // and bans (used by servers)
1323 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1328 if (strcmp(Ptr->key,""))
1330 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1333 log(DEBUG,"add_channel: no key given in JOIN");
1334 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1339 log(DEBUG,"key at %p is %s",key,key);
1340 if (strcasecmp(key,Ptr->key))
1342 log(DEBUG,"add_channel: bad key given in JOIN");
1343 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1348 log(DEBUG,"add_channel: no key");
1350 if (Ptr->inviteonly)
1352 log(DEBUG,"add_channel: channel is +i");
1353 if (user->IsInvited(Ptr->name))
1355 /* user was invited to channel */
1356 /* there may be an optional channel NOTICE here */
1360 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1364 log(DEBUG,"add_channel: channel is not +i");
1368 if (usercount(Ptr) == Ptr->limit)
1370 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1375 log(DEBUG,"add_channel: about to walk banlist");
1377 /* check user against the channel banlist */
1380 if (Ptr->bans.size())
1382 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1384 if (match(user->GetFullHost(),i->data))
1386 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1393 log(DEBUG,"add_channel: bans checked");
1396 if ((Ptr) && (user))
1398 user->RemoveInvite(Ptr->name);
1401 log(DEBUG,"add_channel: invites removed");
1406 log(DEBUG,"Overridden checks");
1414 log(DEBUG,"Passed channel checks");
1416 for (int i =0; i != MAXCHANS; i++)
1418 log(DEBUG,"Check location %d",i);
1419 if (user->chans[i].channel == NULL)
1421 log(DEBUG,"Adding into their channel list at location %d",i);
1425 /* first user in is given ops */
1426 user->chans[i].uc_modes = UCMODE_OP;
1430 user->chans[i].uc_modes = 0;
1432 user->chans[i].channel = Ptr;
1433 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1435 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1437 // use the stamdard J token with no privilages.
1438 char buffer[MAXBUF];
1439 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1440 NetSendToAll(buffer);
1443 log(DEBUG,"Sent JOIN to client");
1447 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1448 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1451 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1452 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1453 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1454 FOREACH_MOD OnUserJoin(user,Ptr);
1458 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1459 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1463 /* remove a channel from a users record, and remove the record from memory
1464 * if the channel has become empty */
1466 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1468 if ((!user) || (!cname))
1470 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1477 if ((!cname) || (!user))
1482 Ptr = FindChan(cname);
1489 FOREACH_MOD OnUserPart(user,Ptr);
1490 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1492 for (int i =0; i != MAXCHANS; i++)
1494 /* zap it from the channel list of the user */
1495 if (user->chans[i].channel == Ptr)
1499 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1503 char buffer[MAXBUF];
1504 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1505 NetSendToAll(buffer);
1514 char buffer[MAXBUF];
1515 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1516 NetSendToAll(buffer);
1519 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1521 user->chans[i].uc_modes = 0;
1522 user->chans[i].channel = NULL;
1523 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1528 /* if there are no users left on the channel */
1529 if (!usercount(Ptr))
1531 chan_hash::iterator iter = chanlist.find(Ptr->name);
1533 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1535 /* kill the record */
1536 if (iter != chanlist.end())
1538 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1539 delete iter->second;
1540 chanlist.erase(iter);
1546 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1548 if ((!src) || (!user) || (!Ptr) || (!reason))
1550 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1557 if ((!Ptr) || (!user) || (!src))
1562 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1564 if (!has_channel(user,Ptr))
1566 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1569 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1571 if (cstatus(src,Ptr) == STATUS_HOP)
1573 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1577 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1583 for (int i =0; i != MAXCHANS; i++)
1585 /* zap it from the channel list of the user */
1586 if (user->chans[i].channel)
1587 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1589 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1590 user->chans[i].uc_modes = 0;
1591 user->chans[i].channel = NULL;
1592 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1597 /* if there are no users left on the channel */
1598 if (!usercount(Ptr))
1600 chan_hash::iterator iter = chanlist.find(Ptr->name);
1602 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1604 /* kill the record */
1605 if (iter != chanlist.end())
1607 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1608 delete iter->second;
1609 chanlist.erase(iter);
1617 /* This function pokes and hacks at a parameter list like the following:
1619 * PART #winbot, #darkgalaxy :m00!
1621 * to turn it into a series of individual calls like this:
1623 * PART #winbot :m00!
1624 * PART #darkgalaxy :m00!
1626 * The seperate calls are sent to a callback function provided by the caller
1627 * (the caller will usually call itself recursively). The callback function
1628 * must be a command handler. Calling this function on a line with no list causes
1629 * no action to be taken. You must provide a starting and ending parameter number
1630 * where the range of the list can be found, useful if you have a terminating
1631 * parameter as above which is actually not part of the list, or parameters
1632 * before the actual list as well. This code is used by many functions which
1633 * can function as "one to list" (see the RFC) */
1635 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1640 char blog[32][MAXBUF];
1641 char blog2[32][MAXBUF];
1642 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1643 char keystr[MAXBUF];
1646 for (int i = 0; i <32; i++)
1649 for (int i = 0; i <32; i++)
1650 strcpy(blog2[i],"");
1653 for (int i = 0; i <10; i++)
1657 parameters[i] = moo;
1662 if (pcnt > 1) /* we have a key to copy */
1664 strcpy(keystr,parameters[1]);
1668 if (!parameters[start])
1672 if (!strchr(parameters[start],','))
1677 for (int i = start; i <= end; i++)
1681 strcat(plist,parameters[i]);
1689 for (int i = 0; i < t; i++)
1691 if (plist[i] == ',')
1694 strcpy(blog[j++],param);
1698 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1703 strcpy(blog[j++],param);
1706 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1711 if ((joins) && (keystr))
1713 if (strchr(keystr,','))
1717 t2 = strlen(keystr);
1718 for (int i = 0; i < t2; i++)
1720 if (keystr[i] == ',')
1723 strcpy(blog2[j++],param);
1727 strcpy(blog2[j++],param);
1732 for (j = 0; j < total; j++)
1738 for (q = end; q < pcnt-1; q++)
1740 if (parameters[q+1])
1742 pars[q-end+1] = parameters[q+1];
1745 if ((joins) && (parameters[1]))
1756 /* repeatedly call the function with the hacked parameter list */
1757 if ((joins) && (pcnt > 1))
1761 // pars[1] already set up and containing key from blog2[j]
1766 pars[1] = parameters[1];
1772 fn(pars,pcnt-(end-start),u);
1780 void handle_join(char **parameters, int pcnt, userrec *user)
1785 if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
1787 if (parameters[0][0] == '#')
1789 Ptr = add_channel(user,parameters[0],parameters[1],false);
1794 void handle_part(char **parameters, int pcnt, userrec *user)
1800 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
1802 del_channel(user,parameters[0],parameters[1],false);
1806 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
1808 del_channel(user,parameters[0],NULL,false);
1812 void handle_kick(char **parameters, int pcnt, userrec *user)
1814 chanrec* Ptr = FindChan(parameters[0]);
1815 userrec* u = Find(parameters[1]);
1819 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
1823 if (!has_channel(u,Ptr))
1825 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
1829 char reason[MAXBUF];
1833 strncpy(reason,parameters[2],MAXBUF);
1834 if (strlen(reason)>MAXKICK)
1836 reason[MAXKICK-1] = '\0';
1839 kick_channel(user,u,Ptr,reason);
1843 strcpy(reason,user->nick);
1844 kick_channel(user,u,Ptr,reason);
1847 // this must be propogated so that channel membership is kept in step network-wide
1849 char buffer[MAXBUF];
1850 snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
1851 NetSendToAll(buffer);
1855 void handle_die(char **parameters, int pcnt, userrec *user)
1857 log(DEBUG,"die: %s",user->nick);
1858 if (!strcmp(parameters[0],diepass))
1860 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
1866 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
1870 void handle_restart(char **parameters, int pcnt, userrec *user)
1872 log(DEBUG,"restart: %s",user->nick);
1873 if (!strcmp(parameters[0],restartpass))
1875 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
1878 /* Will finish this later when i can be arsed :) */
1882 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
1887 void kill_link(userrec *user,const char* r)
1889 user_hash::iterator iter = clientlist.find(user->nick);
1891 char reason[MAXBUF];
1893 strncpy(reason,r,MAXBUF);
1895 if (strlen(reason)>MAXQUIT)
1897 reason[MAXQUIT-1] = '\0';
1900 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1901 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1902 log(DEBUG,"closing fd %d",user->fd);
1904 /* bugfix, cant close() a nonblocking socket (sux!) */
1905 if (user->registered == 7) {
1906 FOREACH_MOD OnUserQuit(user);
1907 WriteCommonExcept(user,"QUIT :%s",reason);
1909 // Q token must go to ALL servers!!!
1910 char buffer[MAXBUF];
1911 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1912 NetSendToAll(buffer);
1915 /* push the socket on a stack of sockets due to be closed at the next opportunity
1916 * 'Client exited' is an exception to this as it means the client side has already
1917 * closed the socket, we don't need to do it.
1919 fd_reap.push_back(user->fd);
1921 bool do_purge = false;
1923 if (user->registered == 7) {
1924 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1928 if (iter != clientlist.end())
1930 log(DEBUG,"deleting user hash value %d",iter->second);
1931 if ((iter->second) && (user->registered == 7)) {
1932 delete iter->second;
1934 clientlist.erase(iter);
1937 if (user->registered == 7) {
1938 purge_empty_chans();
1943 void handle_kill(char **parameters, int pcnt, userrec *user)
1945 userrec *u = Find(parameters[0]);
1946 char killreason[MAXBUF];
1948 log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
1951 if (strcmp(ServerName,u->server))
1954 WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
1955 sprintf(killreason,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
1956 WriteCommonExcept(u,"QUIT :%s",killreason);
1957 // K token must go to ALL servers!!!
1958 char buffer[MAXBUF];
1959 snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
1960 NetSendToAll(buffer);
1962 user_hash::iterator iter = clientlist.find(u->nick);
1963 if (iter != clientlist.end())
1965 log(DEBUG,"deleting user hash value %d",iter->second);
1966 if ((iter->second) && (user->registered == 7)) {
1967 delete iter->second;
1969 clientlist.erase(iter);
1971 purge_empty_chans();
1976 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
1977 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
1978 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
1979 kill_link(u,killreason);
1984 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
1988 void handle_summon(char **parameters, int pcnt, userrec *user)
1990 WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
1993 void handle_users(char **parameters, int pcnt, userrec *user)
1995 WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
1999 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2001 char* Passwd(userrec *user)
2003 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2005 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2013 bool IsDenied(userrec *user)
2015 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2017 if (match(user->host,i->host) && (i->type == CC_DENY))
2027 void handle_pass(char **parameters, int pcnt, userrec *user)
2029 // Check to make sure they havnt registered -- Fix by FCS
2030 if (user->registered == 7)
2032 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
2035 if (!strcasecmp(parameters[0],Passwd(user)))
2037 user->haspassed = true;
2041 void handle_invite(char **parameters, int pcnt, userrec *user)
2043 userrec* u = Find(parameters[0]);
2044 chanrec* c = FindChan(parameters[1]);
2050 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2056 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2065 if (cstatus(user,c) < STATUS_HOP)
2067 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
2071 if (has_channel(u,c))
2073 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
2076 if (!has_channel(user,c))
2078 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
2081 u->InviteTo(c->name);
2082 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2083 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2085 // i token must go to ALL servers!!!
2086 char buffer[MAXBUF];
2087 snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
2088 NetSendToAll(buffer);
2091 void handle_topic(char **parameters, int pcnt, userrec *user)
2097 if (strlen(parameters[0]) <= CHANMAX)
2099 Ptr = FindChan(parameters[0]);
2104 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2105 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2109 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2114 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2121 if (strlen(parameters[0]) <= CHANMAX)
2123 Ptr = FindChan(parameters[0]);
2126 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2128 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
2133 strncpy(topic,parameters[1],MAXBUF);
2134 if (strlen(topic)>MAXTOPIC)
2136 topic[MAXTOPIC-1] = '\0';
2139 strcpy(Ptr->topic,topic);
2140 strcpy(Ptr->setby,user->nick);
2141 Ptr->topicset = time(NULL);
2142 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2144 // t token must go to ALL servers!!!
2145 char buffer[MAXBUF];
2146 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
2147 NetSendToAll(buffer);
2151 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2157 /* sends out an error notice to all connected clients (not to be used
2160 void send_error(char *s)
2162 log(DEBUG,"send_error: %s",s);
2163 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2165 if (isnick(i->second->nick))
2167 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2171 // fix - unregistered connections receive ERROR, not NOTICE
2172 Write(i->second->fd,"ERROR :%s",s);
2177 void Error(int status)
2179 signal (SIGALRM, SIG_IGN);
2180 signal (SIGPIPE, SIG_IGN);
2181 signal (SIGTERM, SIG_IGN);
2182 signal (SIGABRT, SIG_IGN);
2183 signal (SIGSEGV, SIG_IGN);
2184 signal (SIGURG, SIG_IGN);
2185 signal (SIGKILL, SIG_IGN);
2186 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2187 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2192 int main(int argc, char *argv[])
2196 log(DEBUG,"*** InspIRCd starting up!");
2197 if (!FileExists(CONFIG_FILE))
2199 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2200 log(DEBUG,"main: no config");
2201 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2205 if (!strcmp(argv[1],"-nofork")) {
2209 if (InspIRCd() == ERROR)
2211 log(DEBUG,"main: daemon function bailed");
2212 printf("ERROR: could not initialise. Shutting down.\n");
2219 template<typename T> inline string ConvToStr(const T &in)
2222 if (!(tmp << in)) return string();
2226 /* re-allocates a nick in the user_hash after they change nicknames,
2227 * returns a pointer to the new user as it may have moved */
2229 userrec* ReHashNick(char* Old, char* New)
2231 user_hash::iterator newnick;
2232 user_hash::iterator oldnick = clientlist.find(Old);
2234 log(DEBUG,"ReHashNick: %s %s",Old,New);
2236 if (!strcasecmp(Old,New))
2238 log(DEBUG,"old nick is new nick, skipping");
2239 return oldnick->second;
2242 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2244 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2246 clientlist[New] = new userrec();
2247 clientlist[New] = oldnick->second;
2248 /*delete oldnick->second; */
2249 clientlist.erase(oldnick);
2251 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2253 return clientlist[New];
2256 /* adds or updates an entry in the whowas list */
2257 void AddWhoWas(userrec* u)
2259 user_hash::iterator iter = whowas.find(u->nick);
2260 userrec *a = new userrec();
2261 strcpy(a->nick,u->nick);
2262 strcpy(a->ident,u->ident);
2263 strcpy(a->dhost,u->dhost);
2264 strcpy(a->host,u->host);
2265 strcpy(a->fullname,u->fullname);
2266 strcpy(a->server,u->server);
2267 a->signon = u->signon;
2269 /* MAX_WHOWAS: max number of /WHOWAS items
2270 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2271 * can be replaced by a newer one
2274 if (iter == whowas.end())
2276 if (whowas.size() == WHOWAS_MAX)
2278 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2280 // 3600 seconds in an hour ;)
2281 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2285 log(DEBUG,"added WHOWAS entry, purged an old record");
2292 log(DEBUG,"added fresh WHOWAS entry");
2293 whowas[a->nick] = a;
2298 log(DEBUG,"updated WHOWAS entry");
2299 delete iter->second;
2305 /* add a client connection to the sockets list */
2306 void AddClient(int socket, char* host, int port, bool iscached)
2310 char resolved[MAXBUF];
2313 user_hash::iterator iter;
2315 tempnick = ConvToStr(socket) + "-unknown";
2316 sprintf(tn2,"%d-unknown",socket);
2318 iter = clientlist.find(tempnick);
2320 if (iter != clientlist.end()) return;
2323 * It is OK to access the value here this way since we know
2324 * it exists, we just created it above.
2326 * At NO other time should you access a value in a map or a
2327 * hash_map this way.
2329 clientlist[tempnick] = new userrec();
2331 NonBlocking(socket);
2332 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
2334 clientlist[tempnick]->fd = socket;
2335 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2336 strncpy(clientlist[tempnick]->host, host,160);
2337 strncpy(clientlist[tempnick]->dhost, host,160);
2338 strncpy(clientlist[tempnick]->server, ServerName,256);
2339 strncpy(clientlist[tempnick]->ident, "unknown",9);
2340 clientlist[tempnick]->registered = 0;
2341 clientlist[tempnick]->signon = time(NULL);
2342 clientlist[tempnick]->nping = time(NULL)+240;
2343 clientlist[tempnick]->lastping = 1;
2344 clientlist[tempnick]->port = port;
2348 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2352 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2355 // set the registration timeout for this user
2356 unsigned long class_regtimeout = 90;
2357 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2359 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2361 class_regtimeout = (unsigned long)i->registration_timeout;
2366 int class_flood = 0;
2367 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2369 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2371 class_flood = i->flood;
2376 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2377 clientlist[tempnick]->flood = class_flood;
2379 for (int i = 0; i < MAXCHANS; i++)
2381 clientlist[tempnick]->chans[i].channel = NULL;
2382 clientlist[tempnick]->chans[i].uc_modes = 0;
2385 if (clientlist.size() == MAXCLIENTS)
2386 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2389 void handle_names(char **parameters, int pcnt, userrec *user)
2393 if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
2395 c = FindChan(parameters[0]);
2398 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
2400 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
2404 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2408 void handle_privmsg(char **parameters, int pcnt, userrec *user)
2413 user->idle_lastmsg = time(NULL);
2415 if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
2417 if (parameters[0][0] == '#')
2419 chan = FindChan(parameters[0]);
2422 if ((chan->noexternal) && (!has_channel(user,chan)))
2424 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
2427 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
2429 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
2435 FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
2440 ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
2442 // if any users of this channel are on remote servers, broadcast the packet
2443 char buffer[MAXBUF];
2444 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
2445 NetSendToCommon(user,buffer);
2449 /* no such nick/channel */
2450 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2455 dest = Find(parameters[0]);
2458 if (strcmp(dest->awaymsg,""))
2460 /* auto respond with aweh msg */
2461 WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
2466 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
2473 if (!strcmp(dest->server,user->server))
2475 // direct write, same server
2476 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
2480 char buffer[MAXBUF];
2481 snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
2482 NetSendToOne(dest->server,buffer);
2487 /* no such nick/channel */
2488 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2492 void handle_notice(char **parameters, int pcnt, userrec *user)
2497 user->idle_lastmsg = time(NULL);
2499 if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
2501 if (parameters[0][0] == '#')
2503 chan = FindChan(parameters[0]);
2506 if ((chan->noexternal) && (!has_channel(user,chan)))
2508 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
2511 if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
2513 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
2519 FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
2524 ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
2526 // if any users of this channel are on remote servers, broadcast the packet
2527 char buffer[MAXBUF];
2528 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
2529 NetSendToCommon(user,buffer);
2533 /* no such nick/channel */
2534 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2539 dest = Find(parameters[0]);
2544 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
2549 if (!strcmp(dest->server,user->server))
2551 // direct write, same server
2552 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
2556 char buffer[MAXBUF];
2557 snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
2558 NetSendToOne(dest->server,buffer);
2563 /* no such nick/channel */
2564 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2569 void handle_info(char **parameters, int pcnt, userrec *user)
2571 WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
2572 WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
2573 WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
2574 FOREACH_MOD OnInfo(user);
2575 WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
2578 void handle_time(char **parameters, int pcnt, userrec *user)
2581 struct tm * timeinfo;
2584 timeinfo = localtime ( &rawtime );
2585 WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
2589 void handle_whois(char **parameters, int pcnt, userrec *user)
2594 if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
2596 dest = Find(parameters[0]);
2599 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
2600 if (dest->registered == 7)
2602 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
2603 if ((user == dest) || (strchr(user->modes,'o')))
2605 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
2607 if (strcmp(chlist(dest),""))
2609 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
2611 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, GetServerDescription(dest->server).c_str());
2612 if (strcmp(dest->awaymsg,""))
2614 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
2616 if (strchr(dest->modes,'o'))
2618 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
2620 FOREACH_MOD OnWhois(user,dest);
2621 if (!strcasecmp(user->server,dest->server))
2623 // idle time and signon line can only be sent if youre on the same server (according to RFC)
2624 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
2627 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
2631 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2636 /* no such nick/channel */
2637 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2641 void handle_quit(char **parameters, int pcnt, userrec *user)
2643 user_hash::iterator iter = clientlist.find(user->nick);
2646 if (user->registered == 7)
2648 /* theres more to do here, but for now just close the socket */
2651 if (parameters[0][0] == ':')
2655 reason = parameters[0];
2657 if (strlen(reason)>MAXQUIT)
2659 reason[MAXQUIT-1] = '\0';
2662 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
2663 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
2664 WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
2666 char buffer[MAXBUF];
2667 snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
2668 NetSendToAll(buffer);
2672 Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
2673 WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
2674 WriteCommonExcept(user,"QUIT :Client exited");
2676 char buffer[MAXBUF];
2677 snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
2678 NetSendToAll(buffer);
2680 FOREACH_MOD OnUserQuit(user);
2684 /* push the socket on a stack of sockets due to be closed at the next opportunity */
2685 fd_reap.push_back(user->fd);
2687 if (iter != clientlist.end())
2689 clientlist.erase(iter);
2690 log(DEBUG,"deleting user hash value %d",iter->second);
2691 //if ((user) && (user->registered == 7)) {
2696 if (user->registered == 7) {
2697 purge_empty_chans();
2701 void handle_who(char **parameters, int pcnt, userrec *user)
2703 chanrec* Ptr = NULL;
2705 /* theres more to do here, but for now just close the socket */
2708 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
2710 if (user->chans[0].channel)
2712 Ptr = user->chans[0].channel;
2713 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2715 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
2717 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
2723 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
2727 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
2731 if (parameters[0][0] == '#')
2733 Ptr = FindChan(parameters[0]);
2736 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2738 if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
2740 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
2743 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
2747 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2752 userrec* u = Find(parameters[0]);
2753 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, u->nick, u->ident, u->dhost, u->server, u->nick, u->fullname);
2758 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
2760 Ptr = user->chans[0].channel;
2761 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2763 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
2765 if (strchr(i->second->modes,'o'))
2767 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
2771 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
2777 void handle_wallops(char **parameters, int pcnt, userrec *user)
2779 WriteWallOps(user,false,"%s",parameters[0]);
2782 void handle_list(char **parameters, int pcnt, userrec *user)
2786 WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
2787 for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
2789 if ((!i->second->c_private) && (!i->second->secret))
2791 WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
2794 WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
2798 void handle_rehash(char **parameters, int pcnt, userrec *user)
2800 WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
2802 FOREACH_MOD OnRehash();
2803 WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
2809 return clientlist.size();
2813 int usercount_invisible(void)
2817 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2819 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2824 int usercount_opers(void)
2828 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2830 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2835 int usercount_unknown(void)
2839 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2841 if ((i->second->fd) && (i->second->registered != 7))
2847 long chancount(void)
2849 return chanlist.size();
2852 long count_servs(void)
2855 //for (int j = 0; j < 255; j++)
2857 // if (servers[j] != NULL)
2863 long servercount(void)
2865 return count_servs()+1;
2871 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2873 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2879 void handle_lusers(char **parameters, int pcnt, userrec *user)
2881 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
2882 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2883 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2884 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2885 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
2888 void handle_admin(char **parameters, int pcnt, userrec *user)
2890 WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
2891 WriteServ(user->fd,"257 %s :Name - %s",user->nick,AdminName);
2892 WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
2893 WriteServ(user->fd,"258 %s :E-Mail - %s",user->nick,AdminEmail);
2896 void ShowMOTD(userrec *user)
2900 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2903 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2904 for (int i = 0; i != MOTD.size(); i++)
2906 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2908 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2911 void ShowRULES(userrec *user)
2915 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2918 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2919 for (int i = 0; i != RULES.size(); i++)
2921 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2923 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2926 /* shows the message of the day, and any other on-logon stuff */
2927 void ConnectUser(userrec *user)
2929 user->registered = 7;
2930 user->idle_lastmsg = time(NULL);
2931 log(DEBUG,"ConnectUser: %s",user->nick);
2933 if (strcmp(Passwd(user),"") && (!user->haspassed))
2935 kill_link(user,"Invalid password");
2940 kill_link(user,"Unauthorised connection");
2944 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2945 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2946 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2947 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2948 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2949 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);
2950 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);
2952 FOREACH_MOD OnUserConnect(user);
2953 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2955 char buffer[MAXBUF];
2956 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);
2957 NetSendToAll(buffer);
2960 void handle_version(char **parameters, int pcnt, userrec *user)
2962 char Revision[] = "$Revision$";
2964 char *s1 = Revision;
2966 char *v1 = strtok_r(s1," ",&savept);
2968 char *v2 = strtok_r(s1," ",&savept);
2971 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2974 void handle_ping(char **parameters, int pcnt, userrec *user)
2976 WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
2979 void handle_pong(char **parameters, int pcnt, userrec *user)
2981 // set the user as alive so they survive to next ping
2985 void handle_motd(char **parameters, int pcnt, userrec *user)
2990 void handle_rules(char **parameters, int pcnt, userrec *user)
2995 void handle_user(char **parameters, int pcnt, userrec *user)
2997 if (user->registered < 3)
2999 if (isident(parameters[0]) == 0) {
3000 // This kinda Sucks, According to the RFC thou, its either this,
3001 // or "You have already registered" :p -- Craig
3002 WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3005 WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3006 strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3007 strncat(user->ident,parameters[0],IDENTMAX);
3008 strncpy(user->fullname,parameters[3],128);
3009 user->registered = (user->registered | 1);
3014 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3017 /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3018 if (user->registered == 3)
3020 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3025 void handle_userhost(char **parameters, int pcnt, userrec *user)
3027 char Return[MAXBUF],junk[MAXBUF];
3028 sprintf(Return,"302 %s :",user->nick);
3029 for (int i = 0; i < pcnt; i++)
3031 userrec *u = Find(parameters[i]);
3034 if (strchr(u->modes,'o'))
3036 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3037 strcat(Return,junk);
3041 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3042 strcat(Return,junk);
3046 WriteServ(user->fd,Return);
3050 void handle_ison(char **parameters, int pcnt, userrec *user)
3052 char Return[MAXBUF];
3053 sprintf(Return,"303 %s :",user->nick);
3054 for (int i = 0; i < pcnt; i++)
3056 userrec *u = Find(parameters[i]);
3059 strcat(Return,u->nick);
3063 WriteServ(user->fd,Return);
3067 void handle_away(char **parameters, int pcnt, userrec *user)
3071 strcpy(user->awaymsg,parameters[0]);
3072 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3076 strcpy(user->awaymsg,"");
3077 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3081 void handle_whowas(char **parameters, int pcnt, userrec* user)
3083 user_hash::iterator i = whowas.find(parameters[0]);
3085 if (i == whowas.end())
3087 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3088 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3092 time_t rawtime = i->second->signon;
3096 timeinfo = localtime(&rawtime);
3097 strcpy(b,asctime(timeinfo));
3098 b[strlen(b)-1] = '\0';
3100 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3101 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3102 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3107 void handle_trace(char **parameters, int pcnt, userrec *user)
3109 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3113 if (isnick(i->second->nick))
3115 if (strchr(i->second->modes,'o'))
3117 WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3121 WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3126 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3132 void handle_modules(char **parameters, int pcnt, userrec *user)
3134 for (int i = 0; i < module_names.size(); i++)
3136 Version V = modules[i]->GetVersion();
3137 char modulename[MAXBUF];
3138 strncpy(modulename,module_names[i].c_str(),256);
3139 WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,CleanFilename(modulename));
3143 // calls a handler function for a command
3145 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
3147 for (int i = 0; i < cmdlist.size(); i++)
3149 if (!strcasecmp(cmdlist[i].command,commandname))
3151 if (cmdlist[i].handler_function)
3153 if (pcnt>=cmdlist[i].min_params)
3155 if (strchr(user->modes,cmdlist[i].flags_needed))
3157 cmdlist[i].handler_function(parameters,pcnt,user);
3165 void handle_stats(char **parameters, int pcnt, userrec *user)
3171 if (strlen(parameters[0])>1)
3173 /* make the stats query 1 character long */
3174 parameters[0][1] = '\0';
3177 /* stats m (list number of times each command has been used, plus bytecount) */
3178 if (!strcasecmp(parameters[0],"m"))
3180 for (int i = 0; i < cmdlist.size(); i++)
3182 if (cmdlist[i].handler_function)
3184 if (cmdlist[i].use_count)
3186 /* RPL_STATSCOMMANDS */
3187 WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3194 /* stats z (debug and memory info) */
3195 if (!strcasecmp(parameters[0],"z"))
3197 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3198 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3199 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3200 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3201 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3202 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3203 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3204 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3208 if (!strcasecmp(parameters[0],"o"))
3210 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
3212 char LoginName[MAXBUF];
3213 char HostName[MAXBUF];
3214 char OperType[MAXBUF];
3215 ConfValue("oper","name",i,LoginName,&config_f);
3216 ConfValue("oper","host",i,HostName,&config_f);
3217 ConfValue("oper","type",i,OperType,&config_f);
3218 WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3222 /* stats l (show user I/O stats) */
3223 if (!strcasecmp(parameters[0],"l"))
3225 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3226 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3228 if (isnick(i->second->nick))
3230 WriteServ(user->fd,"211 %s :%s:%d %s %d %d %d %d",user->nick,ServerName,i->second->port,i->second->nick,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
3234 WriteServ(user->fd,"211 %s :%s:%d (unknown@%d) %d %d %d %d",user->nick,ServerName,i->second->port,i->second->fd,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
3240 /* stats u (show server uptime) */
3241 if (!strcasecmp(parameters[0],"u"))
3243 time_t current_time = 0;
3244 current_time = time(NULL);
3245 time_t server_uptime = current_time - startup_time;
3247 stime = gmtime(&server_uptime);
3248 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3249 * Craig suggested this, and it seemed a good idea so in it went */
3250 if (stime->tm_year > 70)
3252 WriteServ(user->fd,"242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick,(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
3256 WriteServ(user->fd,"242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick,stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
3260 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3261 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3265 void handle_connect(char **parameters, int pcnt, userrec *user)
3267 char Link_ServerName[1024];
3268 char Link_IPAddr[1024];
3269 char Link_Port[1024];
3270 char Link_Pass[1024];
3274 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
3278 ConfValue("link","name",i,Link_ServerName,&config_f);
3279 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
3280 ConfValue("link","port",i,Link_Port,&config_f);
3281 ConfValue("link","sendpass",i,Link_Pass,&config_f);
3282 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3283 LinkPort = atoi(Link_Port);
3284 if (match(Link_ServerName,parameters[0])) {
3292 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3296 // TODO: Perform a check here to stop a server being linked twice!
3298 WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3300 if (me[defaultRoute])
3302 me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName,me[defaultRoute]->port);
3307 WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
3311 void DoSplitEveryone()
3313 bool go_again = true;
3317 for (int i = 0; i < 32; i++)
3321 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3323 if (strcasecmp(j->GetServerName().c_str(),ServerName))
3326 j->CloseConnection();
3327 me[i]->connectors.erase(j);
3335 log(DEBUG,"Removed server. Will remove clients...");
3336 // iterate through the userlist and remove all users on this server.
3337 // because we're dealing with a mesh, we dont have to deal with anything
3338 // "down-route" from this server (nice huh)
3340 char reason[MAXBUF];
3344 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3346 if (strcasecmp(u->second->server,ServerName))
3348 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
3349 kill_link(u->second,reason);
3359 void handle_squit(char **parameters, int pcnt, userrec *user)
3361 // send out an squit across the mesh and then clear the server list (for local squit)
3364 WriteOpers("SQUIT command issued by %s",user->nick);
3365 char buffer[MAXBUF];
3366 snprintf(buffer,MAXBUF,"& %s",ServerName);
3367 NetSendToAll(buffer);
3372 WriteServ(user->fd,"NOTICE :*** Remote SQUIT not supported yet.");
3376 char islast(const char* s)
3379 for (int j = 0; j < 32; j++)
3383 for (int k = 0; k < me[j]->connectors.size(); k++)
3385 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
3389 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
3399 long map_count(const char* s)
3402 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3404 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
3409 void handle_links(char **parameters, int pcnt, userrec *user)
3411 WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
3412 for (int j = 0; j < 32; j++)
3416 for (int k = 0; k < me[j]->connectors.size(); k++)
3418 WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,me[j]->connectors[k].GetServerName().c_str(),ServerName,me[j]->connectors[k].GetDescription().c_str());
3422 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
3425 void handle_map(char **parameters, int pcnt, userrec *user)
3428 snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
3429 while (strlen(line) < 50)
3431 WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)usercnt())*100));
3432 for (int j = 0; j < 32; j++)
3436 for (int k = 0; k < me[j]->connectors.size(); k++)
3438 snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(me[j]->connectors[k].GetServerName().c_str()),me[j]->connectors[k].GetServerName().c_str());
3439 while (strlen(line) < 50)
3441 WriteServ(user->fd,"%s%d (%.2f%%)",line,map_count(me[j]->connectors[k].GetServerName().c_str()),(float)(((float)map_count(me[j]->connectors[k].GetServerName().c_str())/(float)usercnt())*100));
3445 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
3449 void handle_oper(char **parameters, int pcnt, userrec *user)
3451 char LoginName[MAXBUF];
3452 char Password[MAXBUF];
3453 char OperType[MAXBUF];
3454 char TypeName[MAXBUF];
3455 char Hostname[MAXBUF];
3458 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
3460 ConfValue("oper","name",i,LoginName,&config_f);
3461 ConfValue("oper","password",i,Password,&config_f);
3462 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3464 /* correct oper credentials */
3465 ConfValue("oper","type",i,OperType,&config_f);
3466 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3467 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3468 WriteServ(user->fd,"MODE %s :+o",user->nick);
3469 for (j =0; j < ConfValueEnum("type",&config_f); j++)
3471 ConfValue("type","name",j,TypeName,&config_f);
3472 if (!strcmp(TypeName,OperType))
3474 /* found this oper's opertype */
3475 ConfValue("type","host",j,Hostname,&config_f);
3476 ChangeDisplayedHost(user,Hostname);
3479 if (!strchr(user->modes,'o'))
3481 strcat(user->modes,"o");
3483 FOREACH_MOD OnOper(user);
3488 WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3489 WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3492 void handle_nick(char **parameters, int pcnt, userrec *user)
3496 log(DEBUG,"not enough params for handle_nick");
3501 log(DEBUG,"invalid parameter passed to handle_nick");
3504 if (!strlen(parameters[0]))
3506 log(DEBUG,"zero length new nick passed to handle_nick");
3511 log(DEBUG,"invalid user passed to handle_nick");
3516 log(DEBUG,"invalid old nick passed to handle_nick");
3519 if (!strcasecmp(user->nick,parameters[0]))
3521 log(DEBUG,"old nick is new nick, skipping");
3526 if (strlen(parameters[0]) > 1)
3528 if (parameters[0][0] == ':')
3533 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
3535 WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
3539 if (isnick(parameters[0]) == 0)
3541 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
3545 if (user->registered == 7)
3547 WriteCommon(user,"NICK %s",parameters[0]);
3549 // Q token must go to ALL servers!!!
3550 char buffer[MAXBUF];
3551 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
3552 NetSendToAll(buffer);
3556 /* change the nick of the user in the users_hash */
3557 user = ReHashNick(user->nick, parameters[0]);
3558 /* actually change the nick within the record */
3560 if (!user->nick) return;
3562 strncpy(user->nick, parameters[0],NICKMAX);
3564 log(DEBUG,"new nick set: %s",user->nick);
3566 if (user->registered < 3)
3567 user->registered = (user->registered | 2);
3568 if (user->registered == 3)
3570 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3573 log(DEBUG,"exit nickchange: %s",user->nick);
3576 void force_nickchange(userrec* user,const char* newnick)
3585 strncpy(nick,newnick,MAXBUF);
3587 if (user->registered == 7)
3591 handle_nick(pars,1,user);
3597 int process_parameters(char **command_p,char *parameters)
3602 q = strlen(parameters);
3605 /* no parameters, command_p invalid! */
3608 if (parameters[0] == ':')
3610 command_p[0] = parameters+1;
3615 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
3617 /* only one parameter */
3618 command_p[0] = parameters;
3619 if (parameters[0] == ':')
3621 if (strchr(parameters,' ') != NULL)
3629 command_p[j++] = parameters;
3630 for (int i = 0; i <= q; i++)
3632 if (parameters[i] == ' ')
3634 command_p[j++] = parameters+i+1;
3635 parameters[i] = '\0';
3636 if (command_p[j-1][0] == ':')
3638 *command_p[j-1]++; /* remove dodgy ":" */
3640 /* parameter like this marks end of the sequence */
3644 return j; /* returns total number of items in the list */
3647 void process_command(userrec *user, char* cmd)
3651 char *command_p[127];
3652 char p[MAXBUF], temp[MAXBUF];
3653 int i, j, items, cmd_found;
3655 for (int i = 0; i < 127; i++)
3656 command_p[i] = NULL;
3666 if (!strcmp(cmd,""))
3671 int total_params = 0;
3674 for (int q = 0; q < strlen(cmd)-1; q++)
3676 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
3679 // found a 'trailing', we dont count them after this.
3687 // another phidjit bug...
3688 if (total_params > 126)
3690 kill_link(user,"Protocol violation (1)");
3696 std::string tmp = cmd;
3697 for (int i = 0; i <= MODCOUNT; i++)
3699 std::string oldtmp = tmp;
3700 modules[i]->OnServerRaw(tmp,true);
3703 log(DEBUG,"A Module changed the input string!");
3704 log(DEBUG,"New string: %s",tmp.c_str());
3705 log(DEBUG,"Old string: %s",oldtmp.c_str());
3709 strncpy(cmd,tmp.c_str(),MAXBUF);
3712 if (!strchr(cmd,' '))
3714 /* no parameters, lets skip the formalities and not chop up
3716 log(DEBUG,"About to preprocess command with no params");
3718 command_p[0] = NULL;
3720 for (int i = 0; i <= strlen(cmd); i++)
3722 cmd[i] = toupper(cmd[i]);
3724 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
3731 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
3732 for (int i = 0; i < strlen(temp); i++)
3734 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
3740 /* split the full string into a command plus parameters */
3744 if (strchr(cmd,' '))
3746 for (int i = 0; i <= strlen(cmd); i++)
3748 /* capitalise the command ONLY, leave params intact */
3749 cmd[i] = toupper(cmd[i]);
3750 /* are we nearly there yet?! :P */
3754 parameters = cmd+i+1;
3762 for (int i = 0; i <= strlen(cmd); i++)
3764 cmd[i] = toupper(cmd[i]);
3771 if (strlen(command)>MAXCOMMAND)
3773 kill_link(user,"Protocol violation (2)");
3777 for (int x = 0; x < strlen(command); x++)
3779 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
3781 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
3783 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
3785 kill_link(user,"Protocol violation (3)");
3792 for (int i = 0; i != cmdlist.size(); i++)
3794 if (strcmp(cmdlist[i].command,""))
3796 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
3798 log(DEBUG,"Found matching command");
3802 if (strcmp(parameters,""))
3804 items = process_parameters(command_p,parameters);
3809 command_p[0] = NULL;
3815 command_p[0] = NULL;
3820 log(DEBUG,"Processing command");
3822 /* activity resets the ping pending timer */
3823 user->nping = time(NULL) + 120;
3824 if ((items) < cmdlist[i].min_params)
3826 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
3827 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
3830 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
3832 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
3833 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
3837 /* if the command isnt USER, PASS, or NICK, and nick is empty,
3839 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
3841 if ((!isnick(user->nick)) || (user->registered != 7))
3843 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3844 WriteServ(user->fd,"451 %s :You have not registered",command);
3848 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
3850 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
3851 if (cmdlist[i].handler_function)
3853 /* ikky /stats counters */
3858 user->bytes_in += strlen(temp);
3861 cmdlist[i].use_count++;
3862 cmdlist[i].total_bytes+=strlen(temp);
3865 /* WARNING: nothing may come after the
3866 * command handler call, as the handler
3867 * may free the user structure! */
3869 cmdlist[i].handler_function(command_p,items,user);
3875 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
3876 WriteServ(user->fd,"451 %s :You have not registered",command);
3884 if ((!cmd_found) && (user))
3886 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
3887 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3892 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
3895 /* create the command and push it onto the table */
3896 strcpy(comm.command,cmd);
3897 comm.handler_function = f;
3898 comm.flags_needed = flags;
3899 comm.min_params = minparams;
3901 comm.total_bytes = 0;
3902 cmdlist.push_back(comm);
3903 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
3906 void SetupCommandTable(void)
3908 createcommand("USER",handle_user,0,4);
3909 createcommand("NICK",handle_nick,0,1);
3910 createcommand("QUIT",handle_quit,0,0);
3911 createcommand("VERSION",handle_version,0,0);
3912 createcommand("PING",handle_ping,0,1);
3913 createcommand("PONG",handle_pong,0,1);
3914 createcommand("ADMIN",handle_admin,0,0);
3915 createcommand("PRIVMSG",handle_privmsg,0,2);
3916 createcommand("INFO",handle_info,0,0);
3917 createcommand("TIME",handle_time,0,0);
3918 createcommand("WHOIS",handle_whois,0,1);
3919 createcommand("WALLOPS",handle_wallops,'o',1);
3920 createcommand("NOTICE",handle_notice,0,2);
3921 createcommand("JOIN",handle_join,0,1);
3922 createcommand("NAMES",handle_names,0,1);
3923 createcommand("PART",handle_part,0,1);
3924 createcommand("KICK",handle_kick,0,2);
3925 createcommand("MODE",handle_mode,0,1);
3926 createcommand("TOPIC",handle_topic,0,1);
3927 createcommand("WHO",handle_who,0,1);
3928 createcommand("MOTD",handle_motd,0,0);
3929 createcommand("RULES",handle_rules,0,0);
3930 createcommand("OPER",handle_oper,0,2);
3931 createcommand("LIST",handle_list,0,0);
3932 createcommand("DIE",handle_die,'o',1);
3933 createcommand("RESTART",handle_restart,'o',1);
3934 createcommand("KILL",handle_kill,'o',2);
3935 createcommand("REHASH",handle_rehash,'o',0);
3936 createcommand("LUSERS",handle_lusers,0,0);
3937 createcommand("STATS",handle_stats,0,1);
3938 createcommand("USERHOST",handle_userhost,0,1);
3939 createcommand("AWAY",handle_away,0,0);
3940 createcommand("ISON",handle_ison,0,0);
3941 createcommand("SUMMON",handle_summon,0,0);
3942 createcommand("USERS",handle_users,0,0);
3943 createcommand("INVITE",handle_invite,0,2);
3944 createcommand("PASS",handle_pass,0,1);
3945 createcommand("TRACE",handle_trace,'o',0);
3946 createcommand("WHOWAS",handle_whowas,0,1);
3947 createcommand("CONNECT",handle_connect,'o',1);
3948 createcommand("SQUIT",handle_squit,'o',0);
3949 createcommand("MODULES",handle_modules,'o',0);
3950 createcommand("LINKS",handle_links,0,0);
3951 createcommand("MAP",handle_map,0,0);
3954 void process_buffer(const char* cmdbuf,userrec *user)
3958 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3965 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3968 if (!strcmp(cmdbuf,""))
3972 strncpy(cmd,cmdbuf,MAXBUF);
3973 if (!strcmp(cmd,""))
3977 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3979 cmd[strlen(cmd)-1] = '\0';
3981 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3983 cmd[strlen(cmd)-1] = '\0';
3985 if (!strcmp(cmd,""))
3989 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3991 if ((user) && (cmd))
3993 process_command(user,cmd);
3997 void DoSync(serverrec* serv, char* udp_host)
4000 // send start of sync marker: Y <timestamp>
4001 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
4002 // except the ones its receiving it from.
4003 snprintf(data,MAXBUF,"Y %d",time(NULL));
4004 serv->SendPacket(data,udp_host);
4005 // send users and channels
4006 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
4008 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);
4009 serv->SendPacket(data,udp_host);
4010 if (strcmp(chlist(u->second),""))
4012 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
4013 serv->SendPacket(data,udp_host);
4016 // send channel modes, topics etc...
4017 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
4019 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
4020 serv->SendPacket(data,udp_host);
4021 if (strcmp(c->second->topic,""))
4023 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
4024 serv->SendPacket(data,udp_host);
4026 // send current banlist
4028 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
4030 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
4031 serv->SendPacket(data,udp_host);
4034 // send end of sync marker: E <timestamp>
4035 snprintf(data,MAXBUF,"F %d",time(NULL));
4036 serv->SendPacket(data,udp_host);
4037 // ircd sends its serverlist after the end of sync here
4041 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4043 char* src = strtok(params," ");
4044 char* dest = strtok(NULL," :");
4045 char* text = strtok(NULL,"\r\n");
4048 userrec* user = Find(src);
4051 userrec* dst = Find(dest);
4055 WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
4059 chanrec* d = FindChan(dest);
4062 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
4070 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4072 char* src = strtok(params," ");
4073 char* dest = strtok(NULL," :");
4074 char* text = strtok(NULL,"\r\n");
4077 userrec* user = Find(src);
4080 userrec* dst = Find(dest);
4084 WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
4088 chanrec* d = FindChan(dest);
4091 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
4098 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4100 char* nick = strtok(params," ");
4101 char* from = strtok(NULL," ");
4102 char* channel = strtok(NULL," ");
4103 userrec* u = Find(nick);
4104 userrec* user = Find(from);
4105 chanrec* c = FindChan(channel);
4106 if ((c) && (u) && (user))
4108 u->InviteTo(c->name);
4109 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
4113 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4115 char* setby = strtok(params," ");
4116 char* channel = strtok(NULL," :");
4117 char* topic = strtok(NULL,"\r\n");
4119 userrec* u = Find(setby);
4120 chanrec* c = FindChan(channel);
4123 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
4124 strncpy(c->topic,topic,MAXTOPIC);
4125 strncpy(c->setby,u->nick,NICKMAX);
4130 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4132 char* tm = strtok(params," ");
4133 char* setby = strtok(NULL," ");
4134 char* channel = strtok(NULL," :");
4135 char* topic = strtok(NULL,"\r\n");
4137 time_t TS = atoi(tm);
4138 chanrec* c = FindChan(channel);
4141 // in the case of topics and TS, the *NEWER*
4142 if (TS <= c->topicset)
4144 WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
4145 strncpy(c->topic,topic,MAXTOPIC);
4146 strncpy(c->setby,setby,NICKMAX);
4151 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4154 char original[MAXBUF],target[MAXBUF];
4155 strncpy(original,params,MAXBUF);
4157 char* parameter = strtok(params," ");
4158 strncpy(target,parameter,MAXBUF);
4161 pars[index++] = parameter;
4162 parameter = strtok(NULL," ");
4164 merge_mode(pars,index);
4165 if (FindChan(target))
4167 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
4171 WriteTo(NULL,Find(target),"MODE %s",original);
4175 // m is modes set by users only (not servers) valid targets are channels or users.
4177 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4179 // m blah #chatspike +b *!test@*4
4181 char original[MAXBUF];
4182 strncpy(original,params,MAXBUF);
4184 if (!strchr(params,' '))
4186 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
4192 char* src = strtok(params," ");
4193 userrec* user = Find(src);
4197 log(DEBUG,"Found user: %s",user->nick);
4198 char* parameter = strtok(NULL," ");
4201 pars[index++] = parameter;
4202 parameter = strtok(NULL," ");
4205 log(DEBUG,"Calling merge_mode2");
4206 merge_mode2(pars,index,user);
4211 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4213 char* nick = strtok(params," ");
4214 char* channel = strtok(NULL," :");
4215 char* reason = strtok(NULL,"\r\n");
4216 userrec* user = Find(nick);
4220 if (strcmp(reason,""))
4222 del_channel(user,channel,reason,true);
4226 del_channel(user,channel,NULL,true);
4231 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4233 char* src = strtok(params," ");
4234 char* nick = strtok(NULL," :");
4235 char* reason = strtok(NULL,"\r\n");
4236 char kreason[MAXBUF];
4239 userrec* u = Find(nick);
4240 userrec* user = Find(src);
4244 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
4245 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
4246 snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
4247 kill_link(u,kreason);
4251 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4253 char* nick = strtok(params," :");
4254 char* reason = strtok(NULL,"\r\n");
4257 userrec* user = Find(nick);
4261 if (strlen(reason)>MAXQUIT)
4263 reason[MAXQUIT-1] = '\0';
4267 WriteCommonExcept(user,"QUIT :%s",reason);
4269 user_hash::iterator iter = clientlist.find(user->nick);
4271 if (iter != clientlist.end())
4273 log(DEBUG,"deleting user hash value %d",iter->second);
4274 if ((iter->second) && (user->registered == 7)) {
4275 delete iter->second;
4277 clientlist.erase(iter);
4280 purge_empty_chans();
4284 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4286 char* oldnick = strtok(params," ");
4287 char* newnick = strtok(NULL," ");
4289 userrec* user = Find(oldnick);
4293 WriteCommon(user,"NICK %s",newnick);
4294 user = ReHashNick(user->nick, newnick);
4296 if (!user->nick) return;
4297 strncpy(user->nick, newnick,NICKMAX);
4298 log(DEBUG,"new nick set: %s",user->nick);
4302 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
4303 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4305 char* src = strtok(params," ");
4306 char* dest = strtok(NULL," ");
4307 char* channel = strtok(NULL," :");
4308 char* reason = strtok(NULL,"\r\n");
4310 userrec* s = Find(src);
4311 userrec* d = Find(dest);
4312 chanrec* c = FindChan(channel);
4313 if ((s) && (d) && (c))
4315 kick_channel(s,d,c,reason);
4319 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4321 char* who = strtok(params," :");
4322 char* text = strtok(NULL,"\r\n");
4324 userrec* s = Find(who);
4327 WriteWallOps(s,true,text);
4332 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4334 char* tm = strtok(params," ");
4335 char* nick = strtok(NULL," ");
4336 char* host = strtok(NULL," ");
4337 char* dhost = strtok(NULL," ");
4338 char* ident = strtok(NULL," ");
4339 char* modes = strtok(NULL," ");
4340 char* server = strtok(NULL," :");
4341 char* gecos = strtok(NULL,"\r\n");
4344 time_t TS = atoi(tm);
4345 user_hash::iterator iter = clientlist.find(nick);
4346 if (iter != clientlist.end())
4349 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
4351 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
4352 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
4353 kill_link(iter->second,str);
4355 clientlist[nick] = new userrec();
4356 // remote users have an fd of -1. This is so that our Write abstraction
4357 // routines know to route any messages to this record away to whatever server
4359 clientlist[nick]->fd = -1;
4360 strncpy(clientlist[nick]->nick, nick,NICKMAX);
4361 strncpy(clientlist[nick]->host, host,160);
4362 strncpy(clientlist[nick]->dhost, dhost,160);
4363 strncpy(clientlist[nick]->server, server,256);
4364 strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
4365 strncpy(clientlist[nick]->fullname, gecos,128);
4366 clientlist[nick]->signon = TS;
4367 clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
4368 clientlist[nick]->lastping = 1;
4369 clientlist[nick]->port = 0; // so is this...
4370 clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
4371 clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
4372 for (int i = 0; i < MAXCHANS; i++)
4374 clientlist[nick]->chans[i].channel = NULL;
4375 clientlist[nick]->chans[i].uc_modes = 0;
4379 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4381 long tdiff = time(NULL) - atoi(params);
4383 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
4386 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4388 char* nick = strtok(params," :");
4389 char* gecos = strtok(NULL,"\r\n");
4391 userrec* user = Find(nick);
4394 strncpy(user->fullname,gecos,MAXBUF);
4397 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4399 char* nick = strtok(params," ");
4400 char* host = strtok(NULL," ");
4402 userrec* user = Find(nick);
4405 strncpy(user->dhost,host,160);
4408 void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4411 // + test3.chatspike.net 7010 -2016508415
4412 char* servername = strtok(params," ");
4413 char* ipaddr = strtok(NULL," ");
4414 char* ipport = strtok(NULL," ");
4415 char* cookie = strtok(NULL," ");
4416 log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
4419 bool conn_already = false;
4420 for (int i = 0; i < 32; i++)
4424 for (int j = 0; j < me[i]->connectors.size(); j++)
4426 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),servername))
4428 if (me[i]->connectors[j].GetServerPort() == atoi(ipport))
4430 log(DEBUG,"Already got a connection to %s:%d, ignoring +",ipaddr,atoi(ipport));
4431 conn_already = true;
4438 me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
4441 void handle_R(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4443 char* server = strtok(params," ");
4444 char* data = strtok(NULL,"\r\n");
4445 log(DEBUG,"Forwarded packet '%s' to '%s'",data,server);
4446 NetSendToOne(server,data);
4449 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4452 // The J token currently has no timestamp - this needs looking at
4453 // because it will allow splitriding.
4454 char* nick = strtok(params," ");
4455 char* channel = strtok(NULL," ");
4456 userrec* user = Find(nick);
4459 if ((user != NULL) && (strcmp(channel,"")))
4461 char privilage = '\0';
4462 if (channel[0] != '#')
4464 privilage = channel[0];
4467 add_channel(user,channel,"",true);
4469 // now work out the privilages they should have on each channel
4470 // and send the appropriate servermodes.
4471 for (int i = 0; i != MAXCHANS; i++)
4473 if (user->chans[i].channel)
4475 if (!strcasecmp(user->chans[i].channel->name,channel))
4477 if (privilage == '@')
4479 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
4480 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
4482 if (privilage == '%')
4484 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
4485 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
4487 if (privilage == '+')
4489 user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
4490 WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
4497 channel = strtok(NULL," ");
4501 void NetSendMyRoutingTable()
4503 // send out a line saying what is reachable to us.
4504 // E.g. if A is linked to B C and D, send out:
4506 // if its only linked to B and D send out:
4508 // if it has no links, dont even send out the line at all.
4509 char buffer[MAXBUF];
4510 sprintf(buffer,"$ %s",ServerName);
4511 bool sendit = false;
4512 for (int i = 0; i < 32; i++)
4516 for (int j = 0; j < me[i]->connectors.size(); j++)
4518 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
4520 strncat(buffer," ",MAXBUF);
4521 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
4528 NetSendToAll(buffer);
4531 void handle_dollar(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4533 log(DEBUG,"Storing routing table...");
4534 char* sourceserver = strtok(params," ");
4535 char* server = strtok(NULL," ");
4536 for (int i = 0; i < 32; i++)
4540 for (int j = 0; j < me[i]->connectors.size(); j++)
4542 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),sourceserver))
4544 me[i]->connectors[j].routes.clear();
4545 log(DEBUG,"Found entry for source server.");
4549 me[i]->connectors[j].routes.push_back(server);
4550 log(DEBUG,"*** Stored route: %s -> %s -> %s",ServerName,sourceserver,server);
4551 server = strtok(NULL," ");
4558 log(DEBUG,"Warning! routing table received from nonexistent server!");
4562 void DoSplit(const char* params)
4564 bool go_again = true;
4568 for (int i = 0; i < 32; i++)
4572 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
4574 if (!strcasecmp(j->GetServerName().c_str(),params))
4577 j->CloseConnection();
4578 me[i]->connectors.erase(j);
4586 log(DEBUG,"Removed server. Will remove clients...");
4587 // iterate through the userlist and remove all users on this server.
4588 // because we're dealing with a mesh, we dont have to deal with anything
4589 // "down-route" from this server (nice huh)
4591 char reason[MAXBUF];
4592 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
4596 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
4598 if (!strcasecmp(u->second->server,params))
4600 kill_link(u->second,reason);
4608 // removes a server. Will NOT remove its users!
4610 void RemoveServer(const char* name)
4612 bool go_again = true;
4616 for (int i = 0; i < 32; i++)
4620 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
4622 if (!strcasecmp(j->GetServerName().c_str(),name))
4625 j->CloseConnection();
4626 me[i]->connectors.erase(j);
4636 void handle_amp(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
4638 log(DEBUG,"Netsplit! %s split from mesh, removing!",params);
4639 bool go_again = true;
4643 for (int i = 0; i < 32; i++)
4647 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
4649 if (!strcasecmp(j->GetServerName().c_str(),params))
4652 j->CloseConnection();
4653 me[i]->connectors.erase(j);
4661 log(DEBUG,"Removed server. Will remove clients...");
4662 // iterate through the userlist and remove all users on this server.
4663 // because we're dealing with a mesh, we dont have to deal with anything
4664 // "down-route" from this server (nice huh)
4666 char reason[MAXBUF];
4667 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
4671 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
4673 if (!strcasecmp(u->second->server,params))
4675 kill_link(u->second,reason);
4686 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,char* ipaddr,int port)
4688 char buffer[MAXBUF];
4695 nb_start = time(NULL);
4696 WriteOpers("Server %s is starting netburst.",udp_host);
4697 // now broadcast this new servers address out to all servers that are linked to us,
4698 // except the newcomer. They'll all attempt to connect back to it.
4699 authcookie = rand()*rand();
4700 snprintf(buffer,MAXBUF,"~ %d",authcookie);
4701 NetSendToAll(buffer);
4705 // once stored, this authcookie permits other servers to log in
4706 // without user or password, using it.
4708 auth_cookies.push_back(atoi(params));
4709 log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
4711 // connect back to a server using an authcookie
4713 handle_plus(token,params,source,reply,udp_host);
4717 handle_dollar(token,params,source,reply,udp_host);
4719 // node unreachable - we cant route to a server, sooooo we slit it off.
4720 // servers can generate these for themselves for an squit.
4722 handle_amp(token,params,source,reply,udp_host);
4724 // R <server> <data>
4725 // redirect token, send all of <data> along to the given
4726 // server as this server has been found to still have a route to it
4728 handle_R(token,params,source,reply,udp_host);
4733 reply->SendPacket("!",udp_host);
4743 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
4744 // introduce remote client
4746 handle_N(token,params,source,reply,udp_host);
4748 // a <NICK> :<GECOS>
4749 // change GECOS (SETNAME)
4751 handle_a(token,params,source,reply,udp_host);
4754 // change displayed host (SETHOST)
4756 handle_b(token,params,source,reply,udp_host);
4758 // t <NICK> <CHANNEL> :<TOPIC>
4759 // change a channel topic
4761 handle_t(token,params,source,reply,udp_host);
4763 // i <NICK> <CHANNEL>
4764 // invite a user to a channel
4766 handle_i(token,params,source,reply,udp_host);
4768 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
4769 // kick a user from a channel
4771 handle_k(token,params,source,reply,udp_host);
4773 // n <NICK> <NEWNICK>
4774 // change nickname of client -- a server should only be able to
4775 // change the nicknames of clients that reside on it unless
4778 handle_n(token,params,source,reply,udp_host);
4780 // J <NICK> <CHANLIST>
4781 // Join user to channel list, merge channel permissions
4783 handle_J(token,params,source,reply,udp_host);
4785 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
4786 // change channel topic (netburst only)
4788 handle_T(token,params,source,reply,udp_host);
4790 // M <TARGET> <MODES> [MODE-PARAMETERS]
4791 // Server setting modes on an object
4793 handle_M(token,params,source,reply,udp_host);
4795 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
4796 // User setting modes on an object
4798 handle_m(token,params,source,reply,udp_host);
4800 // P <SOURCE> <TARGET> :<TEXT>
4801 // Send a private/channel message
4803 handle_P(token,params,source,reply,udp_host);
4805 // V <SOURCE> <TARGET> :<TEXT>
4806 // Send a private/channel notice
4808 handle_V(token,params,source,reply,udp_host);
4810 // L <SOURCE> <CHANNEL> :<REASON>
4811 // User parting a channel
4813 handle_L(token,params,source,reply,udp_host);
4815 // Q <SOURCE> :<REASON>
4818 handle_Q(token,params,source,reply,udp_host);
4820 // K <SOURCE> <DEST> :<REASON>
4823 handle_K(token,params,source,reply,udp_host);
4825 // @ <SOURCE> :<TEXT>
4828 handle_AT(token,params,source,reply,udp_host);
4833 WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
4834 handle_F(token,params,source,reply,udp_host);
4836 // tell all the other servers to use this authcookie to connect back again
4837 // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
4838 snprintf(buffer,MAXBUF,"+ %s %s %d %d",udp_host,ipaddr,port,authcookie);
4839 NetSendToAllExcept(udp_host,buffer);
4842 // Send netburst now
4844 WriteOpers("Sending my netburst to %s",udp_host);
4845 DoSync(source,udp_host);
4846 WriteOpers("Send of netburst to %s completed",udp_host);
4847 NetSendMyRoutingTable();
4851 WriteOpers("WARNING! Unknown datagram type '%c'",token);
4857 void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
4859 char response[10240];
4860 char token = udp_msg[0];
4861 char* params = udp_msg + 2;
4862 char finalparam[1024];
4863 strcpy(finalparam," :xxxx");
4864 if (strstr(udp_msg," :")) {
4865 strncpy(finalparam,strstr(udp_msg," :"),1024);
4868 char* cookie = strtok(params," ");
4869 char* servername = strtok(NULL," ");
4870 char* serverdesc = finalparam+2;
4872 WriteOpers("AuthCookie CONNECT from %s (%s)",servername,udp_host);
4874 for (int u = 0; u < auth_cookies.size(); u++)
4876 if (auth_cookies[u] == atoi(cookie))
4878 WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
4881 for (int j = 0; j < 32; j++)
4885 for (int k = 0; k < me[j]->connectors.size(); k++)
4887 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
4889 me[j]->connectors[k].SetServerName(servername);
4890 me[j]->connectors[k].SetDescription(serverdesc);
4891 me[j]->connectors[k].SetState(STATE_CONNECTED);
4892 NetSendMyRoutingTable();
4897 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",udp_host);
4905 // bad cookie, bad bad! go sit in the corner!
4906 WriteOpers("Bad cookie from %s!",servername);
4911 // S test.chatspike.net password portn :ChatSpike InspIRCd test server
4912 char* servername = strtok(params," ");
4913 char* password = strtok(NULL," ");
4914 char* myport = strtok(NULL," ");
4915 char* revision = strtok(NULL," ");
4916 char* serverdesc = finalparam+2;
4918 WriteOpers("CONNECT from %s (%s) (their port: %d)",servername,udp_host,atoi(myport));
4920 ircd_connector* cn = serv->FindHost(servername);
4924 WriteOpers("CONNECT aborted: Server %s already exists from %s",servername,ServerName);
4925 char buffer[MAXBUF];
4926 sprintf(buffer,"E :Server %s already exists!",servername);
4927 serv->SendPacket(buffer,udp_host);
4928 RemoveServer(udp_host);
4932 if (atoi(revision) != GetRevision())
4934 WriteOpers("CONNECT aborted: Could not link to %s, is an incompatible version %s, our version is %d",servername,revision,GetRevision());
4935 char buffer[MAXBUF];
4936 sprintf(buffer,"E :Version number mismatch");
4937 serv->SendPacket(buffer,udp_host);
4938 RemoveServer(udp_host);
4939 RemoveServer(servername);
4943 for (int j = 0; j < serv->connectors.size(); j++)
4945 if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
4947 serv->connectors[j].SetServerName(servername);
4948 serv->connectors[j].SetDescription(serverdesc);
4949 serv->connectors[j].SetServerPort(atoi(myport));
4954 char Link_ServerName[1024];
4955 char Link_IPAddr[1024];
4956 char Link_Port[1024];
4957 char Link_Pass[1024];
4958 char Link_SendPass[1024];
4961 // search for a corresponding <link> block in the config files
4962 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
4964 ConfValue("link","name",i,Link_ServerName,&config_f);
4965 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
4966 ConfValue("link","port",i,Link_Port,&config_f);
4967 ConfValue("link","recvpass",i,Link_Pass,&config_f);
4968 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
4969 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4970 LinkPort = atoi(Link_Port);
4971 if (!strcasecmp(Link_ServerName,servername))
4973 // we have a matching link line -
4974 // send a 'diminutive' server message back...
4975 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4976 serv->SendPacket(response,servername);
4978 for (int t = 0; t < serv->connectors.size(); t++)
4980 if (!strcasecmp(serv->connectors[t].GetServerName().c_str(),servername))
4982 serv->connectors[t].SetState(STATE_CONNECTED);
4989 char buffer[MAXBUF];
4990 sprintf(buffer,"E :Access is denied (no matching link block)");
4991 serv->SendPacket(buffer,udp_host);
4992 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4993 RemoveServer(udp_host);
4994 RemoveServer(servername);
4999 // S test.chatspike.net password :ChatSpike InspIRCd test server
5000 char* servername = strtok(params," ");
5001 char* password = strtok(NULL," ");
5002 char* serverdesc = finalparam+2;
5004 // TODO: we should do a check here to ensure that this server is one we recently initiated a
5005 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
5006 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
5007 // a connect, so put out an oper alert!
5009 // for now, just accept all, we'll fix that later.
5010 WriteOpers("%s accepted our link credentials ",servername);
5012 char Link_ServerName[1024];
5013 char Link_IPAddr[1024];
5014 char Link_Port[1024];
5015 char Link_Pass[1024];
5016 char Link_SendPass[1024];
5019 // search for a corresponding <link> block in the config files
5020 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5022 ConfValue("link","name",i,Link_ServerName,&config_f);
5023 ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5024 ConfValue("link","port",i,Link_Port,&config_f);
5025 ConfValue("link","recvpass",i,Link_Pass,&config_f);
5026 ConfValue("link","sendpass",i,Link_SendPass,&config_f);
5027 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5028 LinkPort = atoi(Link_Port);
5029 if (!strcasecmp(Link_ServerName,servername))
5031 // matching link at this end too, we're all done!
5032 // at this point we must begin key exchange and insert this
5033 // server into our 'active' table.
5034 for (int j = 0; j < 32; j++)
5038 for (int k = 0; k < me[j]->connectors.size(); k++)
5040 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
5042 char buffer[MAXBUF];
5043 me[j]->connectors[k].SetDescription(serverdesc);
5044 me[j]->connectors[k].SetState(STATE_CONNECTED);
5045 sprintf(buffer,"X 0");
5046 serv->SendPacket(buffer,udp_host);
5047 DoSync(me[j],udp_host);
5048 NetSendMyRoutingTable();
5053 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
5058 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
5061 char buffer[MAXBUF];
5062 sprintf(buffer,"E :Access is denied (no matching link block)");
5063 serv->SendPacket(buffer,udp_host);
5064 WriteOpers("CONNECT from %s denied, no matching link block",servername);
5065 RemoveServer(udp_host);
5066 RemoveServer(servername);
5071 char* error_message = finalparam+2;
5072 WriteOpers("ERROR from %s: %s",udp_host,error_message);
5077 serverrec* source_server = NULL;
5079 for (int j = 0; j < 32; j++)
5083 for (int x = 0; x < me[j]->connectors.size(); x++)
5085 log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
5086 if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
5088 if (me[j]->connectors[x].GetState() == STATE_CONNECTED)
5090 // found a valid ircd_connector.
5091 process_restricted_commands(token,params,me[j],serv,udp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
5099 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
5103 int reap_counter = 0;
5107 struct sockaddr_in client, server;
5108 char addrs[MAXBUF][255];
5109 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
5111 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
5112 int selectResult = 0, selectResult2 = 0;
5113 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
5114 char resolvedHost[MAXBUF];
5118 log_file = fopen("ircd.log","a+");
5121 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
5125 log(DEBUG,"InspIRCd: startup: begin");
5129 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
5131 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
5133 SetupCommandTable();
5134 log(DEBUG,"InspIRCd: startup: default command table set up");
5137 if (strcmp(DieValue,""))
5139 printf("WARNING: %s\n\n",DieValue);
5142 log(DEBUG,"InspIRCd: startup: read config");
5144 int count2 = 0, count3 = 0;
5146 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
5148 ConfValue("bind","port",count,configToken,&config_f);
5149 ConfValue("bind","address",count,Addr,&config_f);
5150 ConfValue("bind","type",count,Type,&config_f);
5151 if (!strcmp(Type,"servers"))
5153 char Default[MAXBUF];
5154 strcpy(Default,"no");
5155 ConfValue("bind","default",count,Default,&config_f);
5156 if (strchr(Default,'y'))
5158 defaultRoute = count3;
5159 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
5161 me[count3] = new serverrec(ServerName,100L,false);
5162 me[count3]->CreateListener(Addr,atoi(configToken));
5167 ports[count2] = atoi(configToken);
5168 strcpy(addrs[count2],Addr);
5171 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
5174 UDPportCount = count3;
5176 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
5178 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
5182 /* BugFix By Craig! :p */
5184 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
5186 char modfile[MAXBUF];
5187 ConfValue("module","name",count2,configToken,&config_f);
5188 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
5189 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
5190 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
5191 /* If The File Doesnt exist, Trying to load it
5192 * Will Segfault the IRCd.. So, check to see if
5193 * it Exists, Before Proceeding. */
5194 if (FileExists(modfile))
5196 factory[count] = new ircd_module(modfile);
5197 if (factory[count]->LastError())
5199 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
5200 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
5203 if (factory[count]->factory)
5205 modules[count] = factory[count]->factory->CreateModule();
5206 /* save the module and the module's classfactory, if
5207 * this isnt done, random crashes can occur :/ */
5208 module_names.push_back(modfile);
5212 log(DEBUG,"Unable to load %s",modfile);
5213 sprintf("Unable to load %s\nExiting...\n",modfile);
5216 /* Increase the Count */
5221 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
5222 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
5225 MODCOUNT = count - 1;
5226 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
5228 printf("\nInspIRCd is now running!\n");
5230 startup_time = time(NULL);
5234 log(VERBOSE,"Not forking as -nofork was specified");
5238 if (DaemonSeed() == ERROR)
5240 log(DEBUG,"InspIRCd: startup: can't daemonise");
5241 printf("ERROR: could not go into daemon mode. Shutting down.\n");
5247 /* setup select call */
5248 FD_ZERO(&selectFds);
5249 log(DEBUG,"InspIRCd: startup: zero selects");
5250 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
5252 for (count = 0; count < portCount; count++)
5254 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
5256 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
5259 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5261 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5263 else /* well we at least bound to one socket so we'll continue */
5269 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5271 /* if we didn't bind to anything then abort */
5272 if (boundPortCount == 0)
5274 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5279 length = sizeof (client);
5280 char udp_msg[MAXBUF], udp_host[MAXBUF];
5282 /* main loop, this never returns */
5285 #ifdef _POSIX_PRIORITY_SCHEDULING
5293 user_hash::iterator count2 = clientlist.begin();
5295 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5296 // them in a list, then reap the list every second or so.
5297 if (reap_counter>300)
5299 if (fd_reap.size() > 0)
5301 for( int n = 0; n < fd_reap.size(); n++)
5303 Blocking(fd_reap[n]);
5305 NonBlocking(fd_reap[n]);
5314 FD_ZERO(&serverfds);
5317 for (int x = 0; x != UDPportCount; x++)
5319 FD_SET(me[x]->fd, &serverfds);
5325 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
5328 for (int x = 0; x != UDPportCount; x++)
5330 if (FD_ISSET (me[x]->fd, &serverfds))
5332 char remotehost[MAXBUF],resolved[MAXBUF];
5333 length = sizeof (client);
5334 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
5335 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
5336 if(CleanAndResolve(resolved, remotehost) != TRUE)
5338 strncpy(resolved,remotehost,MAXBUF);
5340 // add to this connections ircd_connector vector
5341 // *FIX* - we need the LOCAL port not the remote port in &client!
5342 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
5347 for (int x = 0; x < UDPportCount; x++)
5349 std::deque<std::string> msgs;
5351 if (me[x]->RecvPacket(msgs, udp_host))
5353 for (int ctr = 0; ctr < msgs.size(); ctr++)
5355 char udp_msg[MAXBUF];
5356 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
5357 if (strlen(udp_msg)<1)
5359 log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
5362 // during a netburst, send all data to all other linked servers
5363 if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
5365 NetSendToAllExcept(udp_host,udp_msg);
5367 FOREACH_MOD OnPacketReceive(udp_msg);
5368 handle_link_packet(udp_msg, udp_host, me[x]);
5375 while (count2 != clientlist.end())
5378 tval.tv_usec = tval.tv_sec = 0;
5380 int total_in_this_set = 0;
5382 user_hash::iterator xcount = count2;
5383 user_hash::iterator endingiter = count2;
5385 if (!count2->second) break;
5388 if (count2->second->fd != 0)
5390 // assemble up to 64 sockets into an fd_set
5391 // to implement a pooling mechanism.
5393 // This should be up to 64x faster than the
5394 // old implementation.
5395 while (total_in_this_set < 64)
5397 if (count2 != clientlist.end())
5399 // we don't check the state of remote users.
5400 if (count2->second->fd > 0)
5402 FD_SET (count2->second->fd, &sfd);
5404 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
5405 // their connection class.
5406 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
5408 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
5409 kill_link(count2->second,"Registration timeout");
5412 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5414 if ((!count2->second->lastping) && (count2->second->registered == 7))
5416 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5417 kill_link(count2->second,"Ping timeout");
5420 Write(count2->second->fd,"PING :%s",ServerName);
5421 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5422 count2->second->lastping = 0;
5423 count2->second->nping = time(NULL)+120;
5427 total_in_this_set++;
5432 endingiter = count2;
5433 count2 = xcount; // roll back to where we were
5439 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
5441 // now loop through all of the items in this pool if any are waiting
5442 //if (selectResult2 > 0)
5443 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
5446 #ifdef _POSIX_PRIORITY_SCHEDULING
5451 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
5453 log(DEBUG,"Reading fd %d",count2a->second->fd);
5454 memset(data, 0, 10240);
5455 result = read(count2a->second->fd, data, 10240);
5460 log(DEBUG,"Read %d characters from socket",result);
5461 userrec* current = count2a->second;
5462 int currfd = current->fd;
5463 char* l = strtok(data,"\n");
5468 if ((floodlines > current->flood) && (current->flood != 0))
5470 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
5471 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
5472 kill_link(current,"Excess flood");
5475 char sanitized[NetBufferSize];
5476 memset(sanitized, 0, NetBufferSize);
5478 for (int pt = 0; pt < strlen(l); pt++)
5482 sanitized[ptt++] = l[pt];
5485 sanitized[ptt] = '\0';
5486 if (strlen(sanitized))
5490 // we're gonna re-scan to check if the nick is gone, after every
5491 // command - if it has, we're gonna bail
5492 bool find_again = false;
5493 process_buffer(sanitized,current);
5495 // look for the user's record in case it's changed
5496 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
5498 if (c2->second->fd == currfd)
5500 // found again, update pointer
5501 current == c2->second;
5510 l = strtok(NULL,"\n");
5515 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
5517 log(DEBUG,"killing: %s",count2a->second->nick);
5518 kill_link(count2a->second,strerror(errno));
5522 // result EAGAIN means nothing read
5523 if (result == EAGAIN)
5531 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
5532 kill_link(count2a->second,"Client exited");
5533 // must bail here? kill_link removes the hash, corrupting the iterator
5534 log(DEBUG,"Bailing from client exit");
5538 else if (result > 0)
5543 for (int q = 0; q < total_in_this_set; q++)
5545 // there is no iterator += operator :(
5546 //if (count2 != clientlist.end())
5553 // set up select call
5554 for (count = 0; count < boundPortCount; count++)
5556 FD_SET (openSockfd[count], &selectFds);
5560 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5562 /* select is reporting a waiting socket. Poll them all to find out which */
5563 if (selectResult > 0)
5565 char target[MAXBUF], resolved[MAXBUF];
5566 for (count = 0; count < boundPortCount; count++)
5568 if (FD_ISSET (openSockfd[count], &selectFds))
5570 length = sizeof (client);
5571 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5573 address_cache::iterator iter = IP.find(client.sin_addr);
5574 bool iscached = false;
5575 if (iter == IP.end())
5577 /* ip isn't in cache, add it */
5578 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5579 if(CleanAndResolve(resolved, target) != TRUE)
5581 strncpy(resolved,target,MAXBUF);
5583 /* hostname now in 'target' */
5584 IP[client.sin_addr] = new string(resolved);
5585 /* hostname in cache */
5589 /* found ip (cached) */
5590 strncpy(resolved, iter->second->c_str(), MAXBUF);
5594 if (incomingSockfd < 0)
5596 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5597 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5601 AddClient(incomingSockfd, resolved, ports[count], iscached);
5602 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5609 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
5612 close (incomingSockfd);