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"
59 #define nspace __gnu_cxx
64 int LogLevel = DEFAULT;
65 char ServerName[MAXBUF];
67 char ServerDesc[MAXBUF];
68 char AdminName[MAXBUF];
69 char AdminEmail[MAXBUF];
70 char AdminNick[MAXBUF];
72 char restartpass[MAXBUF];
76 char PrefixQuit[MAXBUF];
77 char DieValue[MAXBUF];
79 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
80 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
82 time_t startup_time = time(NULL);
83 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
86 extern vector<Module*> modules;
87 std::vector<std::string> module_names;
88 extern vector<ircd_module*> factory;
89 std::vector<int> fd_reap;
97 template<> struct nspace::hash<in_addr>
99 size_t operator()(const struct in_addr &a) const
102 memcpy(&q,&a,sizeof(size_t));
107 template<> struct nspace::hash<string>
109 size_t operator()(const string &s) const
112 static struct hash<const char *> strhash;
124 bool operator()(const string& s1, const string& s2) const
126 char a[MAXBUF],b[MAXBUF];
127 strcpy(a,s1.c_str());
128 strcpy(b,s2.c_str());
129 return (strcasecmp(a,b) == 0);
134 struct InAddr_HashComp
137 bool operator()(const in_addr &s1, const in_addr &s2) const
142 memcpy(&q,&s1,sizeof(size_t));
143 memcpy(&p,&s2,sizeof(size_t));
151 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
152 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
153 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
154 typedef std::deque<command_t> command_table;
160 user_hash clientlist;
163 command_table cmdlist;
170 struct linger linger = { 0 };
171 char bannerBuffer[MAXBUF];
172 int boundPortCount = 0;
173 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
174 int defaultRoute = 0;
178 long MyKey = C.GenKey();
182 int has_channel(userrec *u, chanrec *c);
183 int usercount(chanrec *c);
184 int usercount_i(chanrec *c);
185 void update_stats_l(int fd,int data_out);
186 char* Passwd(userrec *user);
187 bool IsDenied(userrec *user);
188 void AddWhoWas(userrec* u);
190 std::vector<long> auth_cookies;
191 std::stringstream config_f(stringstream::in | stringstream::out);
197 char Revision[] = "$Revision$";
200 char *v1 = strtok_r(s1," ",&savept);
202 char *v2 = strtok_r(s1," ",&savept);
204 return (long)(atof(v2)*10000);
208 std::string getservername()
213 std::string getserverdesc()
218 std::string getnetworkname()
223 std::string getadminname()
228 std::string getadminemail()
233 std::string getadminnick()
238 void log(int level,char *text, ...)
240 char textbuffer[MAXBUF];
243 struct tm * timeinfo;
244 if (level < LogLevel)
248 timeinfo = localtime (&rawtime);
253 va_start (argsPtr, text);
254 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
256 strcpy(b,asctime(timeinfo));
257 b[strlen(b)-1] = ':';
258 fprintf(log_file,"%s %s\n",b,textbuffer);
261 // nofork enabled? display it on terminal too
262 printf("%s %s\n",b,textbuffer);
267 void readfile(file_cache &F, const char* fname)
270 char linebuf[MAXBUF];
272 log(DEBUG,"readfile: loading %s",fname);
274 file = fopen(fname,"r");
279 fgets(linebuf,sizeof(linebuf),file);
280 linebuf[strlen(linebuf)-1]='\0';
281 if (!strcmp(linebuf,""))
287 F.push_back(linebuf);
294 log(DEBUG,"readfile: failed to load file: %s",fname);
296 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
299 void ReadConfig(void)
301 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
304 LoadConf(CONFIG_FILE,&config_f);
306 ConfValue("server","name",0,ServerName,&config_f);
307 ConfValue("server","description",0,ServerDesc,&config_f);
308 ConfValue("server","network",0,Network,&config_f);
309 ConfValue("admin","name",0,AdminName,&config_f);
310 ConfValue("admin","email",0,AdminEmail,&config_f);
311 ConfValue("admin","nick",0,AdminNick,&config_f);
312 ConfValue("files","motd",0,motd,&config_f);
313 ConfValue("files","rules",0,rules,&config_f);
314 ConfValue("power","diepass",0,diepass,&config_f);
315 ConfValue("power","pause",0,pauseval,&config_f);
316 ConfValue("power","restartpass",0,restartpass,&config_f);
317 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
318 ConfValue("die","value",0,DieValue,&config_f);
319 ConfValue("options","loglevel",0,dbg,&config_f);
320 ConfValue("options","netbuffersize",0,NB,&config_f);
321 NetBufferSize = atoi(NB);
322 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
324 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
325 NetBufferSize = 10240;
327 if (!strcmp(dbg,"debug"))
329 if (!strcmp(dbg,"verbose"))
331 if (!strcmp(dbg,"default"))
333 if (!strcmp(dbg,"sparse"))
335 if (!strcmp(dbg,"none"))
338 log(DEBUG,"Reading message of the day");
339 readfile(RULES,rules);
340 log(DEBUG,"Reading connect classes");
342 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
345 ConfValue("connect","allow",i,Value,&config_f);
346 ConfValue("connect","timeout",i,timeout,&config_f);
347 ConfValue("connect","flood",i,flood,&config_f);
348 if (strcmp(Value,""))
350 strcpy(c.host,Value);
353 ConfValue("connect","password",i,Value,&config_f);
354 strcpy(c.pass,Value);
355 c.registration_timeout = 90; // default is 2 minutes
356 c.flood = atoi(flood);
359 c.registration_timeout = atoi(timeout);
361 Classes.push_back(c);
362 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
366 ConfValue("connect","deny",i,Value,&config_f);
367 strcpy(c.host,Value);
369 Classes.push_back(c);
370 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
376 /* write formatted text to a socket, in same format as printf */
378 void Write(int sock,char *text, ...)
382 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
385 char textbuffer[MAXBUF];
389 va_start (argsPtr, text);
390 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
392 sprintf(tb,"%s\r\n",textbuffer);
396 write(sock,tb,strlen(tb));
397 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
401 /* write a server formatted numeric response to a single socket */
403 void WriteServ(int sock, char* text, ...)
407 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
410 char textbuffer[MAXBUF],tb[MAXBUF];
412 va_start (argsPtr, text);
414 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
416 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
420 write(sock,tb,strlen(tb));
421 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
425 /* write text from an originating user to originating user */
427 void WriteFrom(int sock, userrec *user,char* text, ...)
429 if ((!text) || (!user))
431 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
434 char textbuffer[MAXBUF],tb[MAXBUF];
436 va_start (argsPtr, text);
438 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
440 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
444 write(sock,tb,strlen(tb));
445 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
449 /* write text to an destination user from a source user (e.g. user privmsg) */
451 void WriteTo(userrec *source, userrec *dest,char *data, ...)
453 if ((!dest) || (!data))
455 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
458 char textbuffer[MAXBUF],tb[MAXBUF];
460 va_start (argsPtr, data);
461 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
465 // if no source given send it from the server.
468 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
472 WriteFrom(dest->fd,source,"%s",textbuffer);
476 /* write formatted text from a source user to all users on a channel
477 * including the sender (NOT for privmsg, notice etc!) */
479 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
481 if ((!Ptr) || (!user) || (!text))
483 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
486 char textbuffer[MAXBUF];
488 va_start (argsPtr, text);
489 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
491 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
493 if (has_channel(i->second,Ptr))
495 WriteTo(user,i->second,"%s",textbuffer);
500 /* write formatted text from a source user to all users on a channel
501 * including the sender (NOT for privmsg, notice etc!) doesnt send to
502 * users on remote servers */
504 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
506 if ((!Ptr) || (!text))
508 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
511 char textbuffer[MAXBUF];
513 va_start (argsPtr, text);
514 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
516 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
518 if (has_channel(i->second,Ptr))
520 if (i->second->fd != -1)
524 WriteServ(i->second->fd,"%s",textbuffer);
528 WriteTo(user,i->second,"%s",textbuffer);
536 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
538 if ((!Ptr) || (!user) || (!text))
540 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
543 char textbuffer[MAXBUF];
545 va_start (argsPtr, text);
546 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
548 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
552 if (has_channel(i->second,Ptr))
554 WriteServ(i->second->fd,"%s",textbuffer);
561 /* write formatted text from a source user to all users on a channel except
562 * for the sender (for privmsg etc) */
564 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
566 if ((!Ptr) || (!user) || (!text))
568 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
571 char textbuffer[MAXBUF];
573 va_start (argsPtr, text);
574 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
577 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
581 if (has_channel(i->second,Ptr) && (user != i->second))
583 WriteTo(user,i->second,"%s",textbuffer);
590 std::string GetServerDescription(char* servername)
592 for (int j = 0; j < 32; j++)
596 for (int k = 0; k < me[j]->connectors.size(); k++)
598 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
600 return me[j]->connectors[k].GetDescription();
604 return ServerDesc; // not a remote server that can be found, it must be me.
609 /* write a formatted string to all users who share at least one common
610 * channel, including the source user e.g. for use in NICK */
612 void WriteCommon(userrec *u, char* text, ...)
616 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
620 if (u->registered != 7) {
621 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
625 char textbuffer[MAXBUF];
627 va_start (argsPtr, text);
628 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
631 WriteFrom(u->fd,u,"%s",textbuffer);
633 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
637 if (common_channels(u,i->second) && (i->second != u))
639 WriteFrom(i->second->fd,u,"%s",textbuffer);
645 /* write a formatted string to all users who share at least one common
646 * channel, NOT including the source user e.g. for use in QUIT */
648 void WriteCommonExcept(userrec *u, char* text, ...)
652 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
656 if (u->registered != 7) {
657 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
661 char textbuffer[MAXBUF];
663 va_start (argsPtr, text);
664 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
667 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
671 if ((common_channels(u,i->second)) && (u != i->second))
673 WriteFrom(i->second->fd,u,"%s",textbuffer);
679 void WriteOpers(char* text, ...)
683 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
687 char textbuffer[MAXBUF];
689 va_start (argsPtr, text);
690 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
693 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
697 if (strchr(i->second->modes,'o'))
699 if (strchr(i->second->modes,'s'))
701 // send server notices to all with +s
702 // (TODO: needs SNOMASKs)
703 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
710 // returns TRUE of any users on channel C occupy server 'servername'.
712 bool ChanAnyOnThisServer(chanrec *c,char* servername)
714 log(DEBUG,"ChanAnyOnThisServer");
715 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
717 if (has_channel(i->second,c))
719 if (!strcasecmp(i->second->server,servername))
728 // returns true if user 'u' shares any common channels with any users on server 'servername'
730 bool CommonOnThisServer(userrec* u,const char* servername)
732 log(DEBUG,"ChanAnyOnThisServer");
733 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
735 if ((common_channels(u,i->second)) && (u != i->second))
737 if (!strcasecmp(i->second->server,servername))
739 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
748 void NetSendToCommon(userrec* u, char* s)
751 snprintf(buffer,MAXBUF,"%s",s);
753 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
755 for (int j = 0; j < 32; j++)
759 for (int k = 0; k < me[j]->connectors.size(); k++)
761 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
763 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
771 void NetSendToAll(char* s)
774 snprintf(buffer,MAXBUF,"%s",s);
776 log(DEBUG,"NetSendToAll: '%s'",s);
778 for (int j = 0; j < 32; j++)
782 for (int k = 0; k < me[j]->connectors.size(); k++)
784 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
790 void NetSendToAllAlive(char* s)
793 snprintf(buffer,MAXBUF,"%s",s);
795 log(DEBUG,"NetSendToAllAlive: '%s'",s);
797 for (int j = 0; j < 32; j++)
801 for (int k = 0; k < me[j]->connectors.size(); k++)
803 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
805 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
809 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
817 void NetSendToOne(char* target,char* s)
820 snprintf(buffer,MAXBUF,"%s",s);
822 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
824 for (int j = 0; j < 32; j++)
828 for (int k = 0; k < me[j]->connectors.size(); k++)
830 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
832 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
839 void NetSendToAllExcept(const char* target,char* s)
842 snprintf(buffer,MAXBUF,"%s",s);
844 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
846 for (int j = 0; j < 32; j++)
850 for (int k = 0; k < me[j]->connectors.size(); k++)
852 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
854 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
862 void WriteMode(const char* modes, int flags, const char* text, ...)
864 if ((!text) || (!modes) || (!flags))
866 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
870 char textbuffer[MAXBUF];
872 va_start (argsPtr, text);
873 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
876 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
880 bool send_to_user = false;
885 for (int n = 0; n < strlen(modes); n++)
887 if (!hasumode(i->second,modes[n]))
889 send_to_user = false;
894 else if (flags == WM_OR)
896 send_to_user = false;
897 for (int n = 0; n < strlen(modes); n++)
899 if (hasumode(i->second,modes[n]))
909 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
916 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
918 if ((!text) || (!source))
920 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
925 char textbuffer[MAXBUF];
927 va_start (argsPtr, text);
928 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
931 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
935 if (strchr(i->second->modes,'w'))
937 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
945 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
946 NetSendToAll(buffer);
950 /* convert a string to lowercase. Note following special circumstances
951 * taken from RFC 1459. Many "official" server branches still hold to this
952 * rule so i will too;
954 * Because of IRC's scandanavian origin, the characters {}| are
955 * considered to be the lower case equivalents of the characters []\,
956 * respectively. This is a critical issue when determining the
957 * equivalence of two nicknames.
960 void strlower(char *n)
966 for (int i = 0; i != strlen(n); i++)
968 n[i] = tolower(n[i]);
980 /* Find a user record by nickname and return a pointer to it */
982 userrec* Find(string nick)
984 user_hash::iterator iter = clientlist.find(nick);
986 if (iter == clientlist.end())
987 /* Couldn't find it */
993 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
995 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
999 if (i->second->fd == fd)
1001 i->second->bytes_out+=data_out;
1002 i->second->cmds_out++;
1009 /* find a channel record by channel name and return a pointer to it */
1011 chanrec* FindChan(const char* chan)
1015 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1019 chan_hash::iterator iter = chanlist.find(chan);
1021 if (iter == chanlist.end())
1022 /* Couldn't find it */
1025 return iter->second;
1029 void purge_empty_chans(void)
1031 int go_again = 1, purge = 0;
1036 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1039 if (!usercount(i->second))
1041 /* kill the record */
1042 if (i != chanlist.end())
1044 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1054 log(DEBUG,"skipped purge for %s",i->second->name);
1059 log(DEBUG,"completed channel purge, killed %d",purge);
1063 char scratch[MAXBUF];
1064 char sparam[MAXBUF];
1066 char* chanmodes(chanrec *chan)
1070 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1077 if (chan->noexternal)
1079 strncat(scratch,"n",MAXMODES);
1081 if (chan->topiclock)
1083 strncat(scratch,"t",MAXMODES);
1085 if (strcmp(chan->key,""))
1087 strncat(scratch,"k",MAXMODES);
1091 strncat(scratch,"l",MAXMODES);
1093 if (chan->inviteonly)
1095 strncat(scratch,"i",MAXMODES);
1097 if (chan->moderated)
1099 strncat(scratch,"m",MAXMODES);
1103 strncat(scratch,"s",MAXMODES);
1105 if (chan->c_private)
1107 strncat(scratch,"p",MAXMODES);
1109 if (strcmp(chan->key,""))
1111 strncat(sparam,chan->key,MAXBUF);
1116 sprintf(foo," %d",chan->limit);
1117 strncat(sparam,foo,MAXBUF);
1119 if (strlen(chan->custom_modes))
1121 strncat(scratch,chan->custom_modes,MAXMODES);
1122 for (int z = 0; z < strlen(chan->custom_modes); z++)
1124 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1127 strncat(sparam," ",MAXBUF);
1128 strncat(sparam,extparam.c_str(),MAXBUF);
1132 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1133 strncat(scratch,sparam,MAXMODES);
1138 /* compile a userlist of a channel into a string, each nick seperated by
1139 * spaces and op, voice etc status shown as @ and + */
1141 void userlist(userrec *user,chanrec *c)
1143 if ((!c) || (!user))
1145 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1149 sprintf(list,"353 %s = %s :", user->nick, c->name);
1150 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1152 if (has_channel(i->second,c))
1154 if (isnick(i->second->nick))
1156 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1158 /* user is +i, and source not on the channel, does not show
1159 * nick in NAMES list */
1162 strcat(list,cmode(i->second,c));
1163 strcat(list,i->second->nick);
1165 if (strlen(list)>(480-NICKMAX))
1167 /* list overflowed into
1168 * multiple numerics */
1169 WriteServ(user->fd,list);
1170 sprintf(list,"353 %s = %s :", user->nick, c->name);
1175 /* if whats left in the list isnt empty, send it */
1176 if (list[strlen(list)-1] != ':')
1178 WriteServ(user->fd,list);
1182 /* return a count of the users on a specific channel accounting for
1183 * invisible users who won't increase the count. e.g. for /LIST */
1185 int usercount_i(chanrec *c)
1192 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1197 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1201 if (has_channel(i->second,c))
1203 if (isnick(i->second->nick))
1205 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1207 /* user is +i, and source not on the channel, does not show
1208 * nick in NAMES list */
1216 log(DEBUG,"usercount_i: %s %d",c->name,count);
1221 int usercount(chanrec *c)
1228 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1233 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1237 if (has_channel(i->second,c))
1239 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1246 log(DEBUG,"usercount: %s %d",c->name,count);
1251 /* add a channel to a user, creating the record for it if needed and linking
1252 * it to the user record */
1254 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1256 if ((!user) || (!cn))
1258 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1267 strncpy(cname,cn,MAXBUF);
1269 // we MUST declare this wherever we use FOREACH_RESULT
1272 if (strlen(cname) > CHANMAX-1)
1274 cname[CHANMAX-1] = '\0';
1277 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1279 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1281 return NULL; // already on the channel!
1285 if (!FindChan(cname))
1287 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1292 /* create a new one */
1293 log(DEBUG,"add_channel: creating: %s",cname);
1295 chanlist[cname] = new chanrec();
1297 strcpy(chanlist[cname]->name, cname);
1298 chanlist[cname]->topiclock = 1;
1299 chanlist[cname]->noexternal = 1;
1300 chanlist[cname]->created = time(NULL);
1301 strcpy(chanlist[cname]->topic, "");
1302 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1303 chanlist[cname]->topicset = 0;
1304 Ptr = chanlist[cname];
1305 log(DEBUG,"add_channel: created: %s",cname);
1306 /* set created to 2 to indicate user
1307 * is the first in the channel
1308 * and should be given ops */
1314 /* channel exists, just fish out a pointer to its struct */
1315 Ptr = FindChan(cname);
1318 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1320 // the override flag allows us to bypass channel modes
1321 // and bans (used by servers)
1324 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1329 if (strcmp(Ptr->key,""))
1331 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1334 log(DEBUG,"add_channel: no key given in JOIN");
1335 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1340 log(DEBUG,"key at %p is %s",key,key);
1341 if (strcasecmp(key,Ptr->key))
1343 log(DEBUG,"add_channel: bad key given in JOIN");
1344 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1349 log(DEBUG,"add_channel: no key");
1351 if (Ptr->inviteonly)
1353 log(DEBUG,"add_channel: channel is +i");
1354 if (user->IsInvited(Ptr->name))
1356 /* user was invited to channel */
1357 /* there may be an optional channel NOTICE here */
1361 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1365 log(DEBUG,"add_channel: channel is not +i");
1369 if (usercount(Ptr) == Ptr->limit)
1371 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1376 log(DEBUG,"add_channel: about to walk banlist");
1378 /* check user against the channel banlist */
1381 if (Ptr->bans.size())
1383 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1385 if (match(user->GetFullHost(),i->data))
1387 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1394 log(DEBUG,"add_channel: bans checked");
1397 if ((Ptr) && (user))
1399 user->RemoveInvite(Ptr->name);
1402 log(DEBUG,"add_channel: invites removed");
1407 log(DEBUG,"Overridden checks");
1415 log(DEBUG,"Passed channel checks");
1417 for (int i =0; i != MAXCHANS; i++)
1419 log(DEBUG,"Check location %d",i);
1420 if (user->chans[i].channel == NULL)
1422 log(DEBUG,"Adding into their channel list at location %d",i);
1426 /* first user in is given ops */
1427 user->chans[i].uc_modes = UCMODE_OP;
1431 user->chans[i].uc_modes = 0;
1433 user->chans[i].channel = Ptr;
1434 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1436 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1438 // use the stamdard J token with no privilages.
1439 char buffer[MAXBUF];
1440 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1441 NetSendToAll(buffer);
1444 log(DEBUG,"Sent JOIN to client");
1448 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1449 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1452 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1453 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1454 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1455 FOREACH_MOD OnUserJoin(user,Ptr);
1459 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1460 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1464 /* remove a channel from a users record, and remove the record from memory
1465 * if the channel has become empty */
1467 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1469 if ((!user) || (!cname))
1471 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1478 if ((!cname) || (!user))
1483 Ptr = FindChan(cname);
1490 FOREACH_MOD OnUserPart(user,Ptr);
1491 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1493 for (int i =0; i != MAXCHANS; i++)
1495 /* zap it from the channel list of the user */
1496 if (user->chans[i].channel == Ptr)
1500 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1504 char buffer[MAXBUF];
1505 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1506 NetSendToAll(buffer);
1515 char buffer[MAXBUF];
1516 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1517 NetSendToAll(buffer);
1520 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1522 user->chans[i].uc_modes = 0;
1523 user->chans[i].channel = NULL;
1524 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1529 /* if there are no users left on the channel */
1530 if (!usercount(Ptr))
1532 chan_hash::iterator iter = chanlist.find(Ptr->name);
1534 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1536 /* kill the record */
1537 if (iter != chanlist.end())
1539 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1540 delete iter->second;
1541 chanlist.erase(iter);
1547 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1549 if ((!src) || (!user) || (!Ptr) || (!reason))
1551 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1558 if ((!Ptr) || (!user) || (!src))
1563 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1565 if (!has_channel(user,Ptr))
1567 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1570 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1572 if (cstatus(src,Ptr) == STATUS_HOP)
1574 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1578 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1584 for (int i =0; i != MAXCHANS; i++)
1586 /* zap it from the channel list of the user */
1587 if (user->chans[i].channel)
1588 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1590 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1591 user->chans[i].uc_modes = 0;
1592 user->chans[i].channel = NULL;
1593 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1598 /* if there are no users left on the channel */
1599 if (!usercount(Ptr))
1601 chan_hash::iterator iter = chanlist.find(Ptr->name);
1603 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1605 /* kill the record */
1606 if (iter != chanlist.end())
1608 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1609 delete iter->second;
1610 chanlist.erase(iter);
1618 /* This function pokes and hacks at a parameter list like the following:
1620 * PART #winbot, #darkgalaxy :m00!
1622 * to turn it into a series of individual calls like this:
1624 * PART #winbot :m00!
1625 * PART #darkgalaxy :m00!
1627 * The seperate calls are sent to a callback function provided by the caller
1628 * (the caller will usually call itself recursively). The callback function
1629 * must be a command handler. Calling this function on a line with no list causes
1630 * no action to be taken. You must provide a starting and ending parameter number
1631 * where the range of the list can be found, useful if you have a terminating
1632 * parameter as above which is actually not part of the list, or parameters
1633 * before the actual list as well. This code is used by many functions which
1634 * can function as "one to list" (see the RFC) */
1636 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1641 char blog[32][MAXBUF];
1642 char blog2[32][MAXBUF];
1643 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1644 char keystr[MAXBUF];
1647 for (int i = 0; i <32; i++)
1650 for (int i = 0; i <32; i++)
1651 strcpy(blog2[i],"");
1654 for (int i = 0; i <10; i++)
1658 parameters[i] = moo;
1663 if (pcnt > 1) /* we have a key to copy */
1665 strcpy(keystr,parameters[1]);
1669 if (!parameters[start])
1673 if (!strchr(parameters[start],','))
1678 for (int i = start; i <= end; i++)
1682 strcat(plist,parameters[i]);
1690 for (int i = 0; i < t; i++)
1692 if (plist[i] == ',')
1695 strcpy(blog[j++],param);
1699 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1704 strcpy(blog[j++],param);
1707 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1712 if ((joins) && (keystr))
1714 if (strchr(keystr,','))
1718 t2 = strlen(keystr);
1719 for (int i = 0; i < t2; i++)
1721 if (keystr[i] == ',')
1724 strcpy(blog2[j++],param);
1728 strcpy(blog2[j++],param);
1733 for (j = 0; j < total; j++)
1739 for (q = end; q < pcnt-1; q++)
1741 if (parameters[q+1])
1743 pars[q-end+1] = parameters[q+1];
1746 if ((joins) && (parameters[1]))
1757 /* repeatedly call the function with the hacked parameter list */
1758 if ((joins) && (pcnt > 1))
1762 // pars[1] already set up and containing key from blog2[j]
1767 pars[1] = parameters[1];
1773 fn(pars,pcnt-(end-start),u);
1782 void kill_link(userrec *user,const char* r)
1784 user_hash::iterator iter = clientlist.find(user->nick);
1786 char reason[MAXBUF];
1788 strncpy(reason,r,MAXBUF);
1790 if (strlen(reason)>MAXQUIT)
1792 reason[MAXQUIT-1] = '\0';
1795 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1796 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1797 log(DEBUG,"closing fd %d",user->fd);
1799 /* bugfix, cant close() a nonblocking socket (sux!) */
1800 if (user->registered == 7) {
1801 FOREACH_MOD OnUserQuit(user);
1802 WriteCommonExcept(user,"QUIT :%s",reason);
1804 // Q token must go to ALL servers!!!
1805 char buffer[MAXBUF];
1806 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1807 NetSendToAll(buffer);
1810 /* push the socket on a stack of sockets due to be closed at the next opportunity
1811 * 'Client exited' is an exception to this as it means the client side has already
1812 * closed the socket, we don't need to do it.
1814 fd_reap.push_back(user->fd);
1816 bool do_purge = false;
1818 if (user->registered == 7) {
1819 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1823 if (iter != clientlist.end())
1825 log(DEBUG,"deleting user hash value %d",iter->second);
1826 if ((iter->second) && (user->registered == 7)) {
1827 delete iter->second;
1829 clientlist.erase(iter);
1832 if (user->registered == 7) {
1833 purge_empty_chans();
1839 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1841 char* Passwd(userrec *user)
1843 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1845 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1853 bool IsDenied(userrec *user)
1855 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1857 if (match(user->host,i->host) && (i->type == CC_DENY))
1868 /* sends out an error notice to all connected clients (not to be used
1871 void send_error(char *s)
1873 log(DEBUG,"send_error: %s",s);
1874 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1876 if (isnick(i->second->nick))
1878 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1882 // fix - unregistered connections receive ERROR, not NOTICE
1883 Write(i->second->fd,"ERROR :%s",s);
1888 void Error(int status)
1890 signal (SIGALRM, SIG_IGN);
1891 signal (SIGPIPE, SIG_IGN);
1892 signal (SIGTERM, SIG_IGN);
1893 signal (SIGABRT, SIG_IGN);
1894 signal (SIGSEGV, SIG_IGN);
1895 signal (SIGURG, SIG_IGN);
1896 signal (SIGKILL, SIG_IGN);
1897 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1898 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1903 int main(int argc, char *argv[])
1907 log(DEBUG,"*** InspIRCd starting up!");
1908 if (!FileExists(CONFIG_FILE))
1910 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1911 log(DEBUG,"main: no config");
1912 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1916 if (!strcmp(argv[1],"-nofork")) {
1920 if (InspIRCd() == ERROR)
1922 log(DEBUG,"main: daemon function bailed");
1923 printf("ERROR: could not initialise. Shutting down.\n");
1930 template<typename T> inline string ConvToStr(const T &in)
1933 if (!(tmp << in)) return string();
1937 /* re-allocates a nick in the user_hash after they change nicknames,
1938 * returns a pointer to the new user as it may have moved */
1940 userrec* ReHashNick(char* Old, char* New)
1942 user_hash::iterator newnick;
1943 user_hash::iterator oldnick = clientlist.find(Old);
1945 log(DEBUG,"ReHashNick: %s %s",Old,New);
1947 if (!strcasecmp(Old,New))
1949 log(DEBUG,"old nick is new nick, skipping");
1950 return oldnick->second;
1953 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1955 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1957 clientlist[New] = new userrec();
1958 clientlist[New] = oldnick->second;
1959 /*delete oldnick->second; */
1960 clientlist.erase(oldnick);
1962 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1964 return clientlist[New];
1967 /* adds or updates an entry in the whowas list */
1968 void AddWhoWas(userrec* u)
1970 user_hash::iterator iter = whowas.find(u->nick);
1971 userrec *a = new userrec();
1972 strcpy(a->nick,u->nick);
1973 strcpy(a->ident,u->ident);
1974 strcpy(a->dhost,u->dhost);
1975 strcpy(a->host,u->host);
1976 strcpy(a->fullname,u->fullname);
1977 strcpy(a->server,u->server);
1978 a->signon = u->signon;
1980 /* MAX_WHOWAS: max number of /WHOWAS items
1981 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1982 * can be replaced by a newer one
1985 if (iter == whowas.end())
1987 if (whowas.size() == WHOWAS_MAX)
1989 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1991 // 3600 seconds in an hour ;)
1992 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
1996 log(DEBUG,"added WHOWAS entry, purged an old record");
2003 log(DEBUG,"added fresh WHOWAS entry");
2004 whowas[a->nick] = a;
2009 log(DEBUG,"updated WHOWAS entry");
2010 delete iter->second;
2016 /* add a client connection to the sockets list */
2017 void AddClient(int socket, char* host, int port, bool iscached)
2021 char resolved[MAXBUF];
2024 user_hash::iterator iter;
2026 tempnick = ConvToStr(socket) + "-unknown";
2027 sprintf(tn2,"%d-unknown",socket);
2029 iter = clientlist.find(tempnick);
2031 if (iter != clientlist.end()) return;
2034 * It is OK to access the value here this way since we know
2035 * it exists, we just created it above.
2037 * At NO other time should you access a value in a map or a
2038 * hash_map this way.
2040 clientlist[tempnick] = new userrec();
2042 NonBlocking(socket);
2043 log(DEBUG,"AddClient: %d %s %d",socket,host,port);
2045 clientlist[tempnick]->fd = socket;
2046 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2047 strncpy(clientlist[tempnick]->host, host,160);
2048 strncpy(clientlist[tempnick]->dhost, host,160);
2049 strncpy(clientlist[tempnick]->server, ServerName,256);
2050 strncpy(clientlist[tempnick]->ident, "unknown",9);
2051 clientlist[tempnick]->registered = 0;
2052 clientlist[tempnick]->signon = time(NULL);
2053 clientlist[tempnick]->nping = time(NULL)+240;
2054 clientlist[tempnick]->lastping = 1;
2055 clientlist[tempnick]->port = port;
2059 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2063 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2066 // set the registration timeout for this user
2067 unsigned long class_regtimeout = 90;
2068 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2070 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2072 class_regtimeout = (unsigned long)i->registration_timeout;
2077 int class_flood = 0;
2078 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2080 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2082 class_flood = i->flood;
2087 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2088 clientlist[tempnick]->flood = class_flood;
2090 for (int i = 0; i < MAXCHANS; i++)
2092 clientlist[tempnick]->chans[i].channel = NULL;
2093 clientlist[tempnick]->chans[i].uc_modes = 0;
2096 if (clientlist.size() == MAXCLIENTS)
2097 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2103 return clientlist.size();
2107 int usercount_invisible(void)
2111 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2113 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2118 int usercount_opers(void)
2122 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2124 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2129 int usercount_unknown(void)
2133 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2135 if ((i->second->fd) && (i->second->registered != 7))
2141 long chancount(void)
2143 return chanlist.size();
2146 long count_servs(void)
2149 //for (int j = 0; j < 255; j++)
2151 // if (servers[j] != NULL)
2157 long servercount(void)
2159 return count_servs()+1;
2165 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2167 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2173 void ShowMOTD(userrec *user)
2177 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2180 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2181 for (int i = 0; i != MOTD.size(); i++)
2183 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2185 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2188 void ShowRULES(userrec *user)
2192 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2195 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2196 for (int i = 0; i != RULES.size(); i++)
2198 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2200 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2203 /* shows the message of the day, and any other on-logon stuff */
2204 void ConnectUser(userrec *user)
2206 user->registered = 7;
2207 user->idle_lastmsg = time(NULL);
2208 log(DEBUG,"ConnectUser: %s",user->nick);
2210 if (strcmp(Passwd(user),"") && (!user->haspassed))
2212 kill_link(user,"Invalid password");
2217 kill_link(user,"Unauthorised connection");
2221 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2222 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2223 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2224 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2225 WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2226 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);
2227 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);
2229 FOREACH_MOD OnUserConnect(user);
2230 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2232 char buffer[MAXBUF];
2233 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);
2234 NetSendToAll(buffer);
2237 void handle_version(char **parameters, int pcnt, userrec *user)
2239 char Revision[] = "$Revision$";
2241 char *s1 = Revision;
2243 char *v1 = strtok_r(s1," ",&savept);
2245 char *v2 = strtok_r(s1," ",&savept);
2248 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2252 // calls a handler function for a command
2254 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2256 for (int i = 0; i < cmdlist.size(); i++)
2258 if (!strcasecmp(cmdlist[i].command,commandname))
2260 if (cmdlist[i].handler_function)
2262 if (pcnt>=cmdlist[i].min_params)
2264 if (strchr(user->modes,cmdlist[i].flags_needed))
2266 cmdlist[i].handler_function(parameters,pcnt,user);
2274 void DoSplitEveryone()
2276 bool go_again = true;
2280 for (int i = 0; i < 32; i++)
2284 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2286 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2289 j->CloseConnection();
2290 me[i]->connectors.erase(j);
2298 log(DEBUG,"Removed server. Will remove clients...");
2299 // iterate through the userlist and remove all users on this server.
2300 // because we're dealing with a mesh, we dont have to deal with anything
2301 // "down-route" from this server (nice huh)
2303 char reason[MAXBUF];
2307 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2309 if (strcasecmp(u->second->server,ServerName))
2311 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2312 kill_link(u->second,reason);
2322 char islast(const char* s)
2325 for (int j = 0; j < 32; j++)
2329 for (int k = 0; k < me[j]->connectors.size(); k++)
2331 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2335 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2345 long map_count(const char* s)
2348 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2350 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2356 void force_nickchange(userrec* user,const char* newnick)
2365 strncpy(nick,newnick,MAXBUF);
2367 if (user->registered == 7)
2371 handle_nick(pars,1,user);
2377 int process_parameters(char **command_p,char *parameters)
2382 q = strlen(parameters);
2385 /* no parameters, command_p invalid! */
2388 if (parameters[0] == ':')
2390 command_p[0] = parameters+1;
2395 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2397 /* only one parameter */
2398 command_p[0] = parameters;
2399 if (parameters[0] == ':')
2401 if (strchr(parameters,' ') != NULL)
2409 command_p[j++] = parameters;
2410 for (int i = 0; i <= q; i++)
2412 if (parameters[i] == ' ')
2414 command_p[j++] = parameters+i+1;
2415 parameters[i] = '\0';
2416 if (command_p[j-1][0] == ':')
2418 *command_p[j-1]++; /* remove dodgy ":" */
2420 /* parameter like this marks end of the sequence */
2424 return j; /* returns total number of items in the list */
2427 void process_command(userrec *user, char* cmd)
2431 char *command_p[127];
2432 char p[MAXBUF], temp[MAXBUF];
2433 int i, j, items, cmd_found;
2435 for (int i = 0; i < 127; i++)
2436 command_p[i] = NULL;
2446 if (!strcmp(cmd,""))
2451 int total_params = 0;
2454 for (int q = 0; q < strlen(cmd)-1; q++)
2456 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2459 // found a 'trailing', we dont count them after this.
2467 // another phidjit bug...
2468 if (total_params > 126)
2470 kill_link(user,"Protocol violation (1)");
2476 std::string tmp = cmd;
2477 for (int i = 0; i <= MODCOUNT; i++)
2479 std::string oldtmp = tmp;
2480 modules[i]->OnServerRaw(tmp,true);
2483 log(DEBUG,"A Module changed the input string!");
2484 log(DEBUG,"New string: %s",tmp.c_str());
2485 log(DEBUG,"Old string: %s",oldtmp.c_str());
2489 strncpy(cmd,tmp.c_str(),MAXBUF);
2492 if (!strchr(cmd,' '))
2494 /* no parameters, lets skip the formalities and not chop up
2496 log(DEBUG,"About to preprocess command with no params");
2498 command_p[0] = NULL;
2500 for (int i = 0; i <= strlen(cmd); i++)
2502 cmd[i] = toupper(cmd[i]);
2504 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2511 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2512 for (int i = 0; i < strlen(temp); i++)
2514 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2520 /* split the full string into a command plus parameters */
2524 if (strchr(cmd,' '))
2526 for (int i = 0; i <= strlen(cmd); i++)
2528 /* capitalise the command ONLY, leave params intact */
2529 cmd[i] = toupper(cmd[i]);
2530 /* are we nearly there yet?! :P */
2534 parameters = cmd+i+1;
2542 for (int i = 0; i <= strlen(cmd); i++)
2544 cmd[i] = toupper(cmd[i]);
2551 if (strlen(command)>MAXCOMMAND)
2553 kill_link(user,"Protocol violation (2)");
2557 for (int x = 0; x < strlen(command); x++)
2559 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2561 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2563 if (!strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
2565 kill_link(user,"Protocol violation (3)");
2572 for (int i = 0; i != cmdlist.size(); i++)
2574 if (strcmp(cmdlist[i].command,""))
2576 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2578 log(DEBUG,"Found matching command");
2582 if (strcmp(parameters,""))
2584 items = process_parameters(command_p,parameters);
2589 command_p[0] = NULL;
2595 command_p[0] = NULL;
2600 log(DEBUG,"Processing command");
2602 /* activity resets the ping pending timer */
2603 user->nping = time(NULL) + 120;
2604 if ((items) < cmdlist[i].min_params)
2606 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2607 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2610 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2612 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2613 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2617 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2619 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2621 if ((!isnick(user->nick)) || (user->registered != 7))
2623 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2624 WriteServ(user->fd,"451 %s :You have not registered",command);
2628 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2630 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2631 if (cmdlist[i].handler_function)
2633 /* ikky /stats counters */
2638 user->bytes_in += strlen(temp);
2641 cmdlist[i].use_count++;
2642 cmdlist[i].total_bytes+=strlen(temp);
2645 /* WARNING: nothing may come after the
2646 * command handler call, as the handler
2647 * may free the user structure! */
2649 cmdlist[i].handler_function(command_p,items,user);
2655 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2656 WriteServ(user->fd,"451 %s :You have not registered",command);
2664 if ((!cmd_found) && (user))
2666 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2667 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2672 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2675 /* create the command and push it onto the table */
2676 strcpy(comm.command,cmd);
2677 comm.handler_function = f;
2678 comm.flags_needed = flags;
2679 comm.min_params = minparams;
2681 comm.total_bytes = 0;
2682 cmdlist.push_back(comm);
2683 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2686 void SetupCommandTable(void)
2688 createcommand("USER",handle_user,0,4);
2689 createcommand("NICK",handle_nick,0,1);
2690 createcommand("QUIT",handle_quit,0,0);
2691 createcommand("VERSION",handle_version,0,0);
2692 createcommand("PING",handle_ping,0,1);
2693 createcommand("PONG",handle_pong,0,1);
2694 createcommand("ADMIN",handle_admin,0,0);
2695 createcommand("PRIVMSG",handle_privmsg,0,2);
2696 createcommand("INFO",handle_info,0,0);
2697 createcommand("TIME",handle_time,0,0);
2698 createcommand("WHOIS",handle_whois,0,1);
2699 createcommand("WALLOPS",handle_wallops,'o',1);
2700 createcommand("NOTICE",handle_notice,0,2);
2701 createcommand("JOIN",handle_join,0,1);
2702 createcommand("NAMES",handle_names,0,1);
2703 createcommand("PART",handle_part,0,1);
2704 createcommand("KICK",handle_kick,0,2);
2705 createcommand("MODE",handle_mode,0,1);
2706 createcommand("TOPIC",handle_topic,0,1);
2707 createcommand("WHO",handle_who,0,1);
2708 createcommand("MOTD",handle_motd,0,0);
2709 createcommand("RULES",handle_rules,0,0);
2710 createcommand("OPER",handle_oper,0,2);
2711 createcommand("LIST",handle_list,0,0);
2712 createcommand("DIE",handle_die,'o',1);
2713 createcommand("RESTART",handle_restart,'o',1);
2714 createcommand("KILL",handle_kill,'o',2);
2715 createcommand("REHASH",handle_rehash,'o',0);
2716 createcommand("LUSERS",handle_lusers,0,0);
2717 createcommand("STATS",handle_stats,0,1);
2718 createcommand("USERHOST",handle_userhost,0,1);
2719 createcommand("AWAY",handle_away,0,0);
2720 createcommand("ISON",handle_ison,0,0);
2721 createcommand("SUMMON",handle_summon,0,0);
2722 createcommand("USERS",handle_users,0,0);
2723 createcommand("INVITE",handle_invite,0,2);
2724 createcommand("PASS",handle_pass,0,1);
2725 createcommand("TRACE",handle_trace,'o',0);
2726 createcommand("WHOWAS",handle_whowas,0,1);
2727 createcommand("CONNECT",handle_connect,'o',1);
2728 createcommand("SQUIT",handle_squit,'o',0);
2729 createcommand("MODULES",handle_modules,'o',0);
2730 createcommand("LINKS",handle_links,0,0);
2731 createcommand("MAP",handle_map,0,0);
2734 void process_buffer(const char* cmdbuf,userrec *user)
2738 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2745 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2748 if (!strcmp(cmdbuf,""))
2752 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2754 strncpy(cmd,cmdbuf,MAXBUF);
2755 if (!strcmp(cmd,""))
2759 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2761 cmd[strlen(cmd)-1] = '\0';
2763 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2765 cmd[strlen(cmd)-1] = '\0';
2768 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2770 cmd[strlen(cmd)-1] = '\0';
2773 if (!strcmp(cmd,""))
2777 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2779 if ((user) && (cmd))
2781 process_command(user,cmd);
2785 void DoSync(serverrec* serv, char* tcp_host)
2788 log(DEBUG,"Sending sync");
2789 // send start of sync marker: Y <timestamp>
2790 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2791 // except the ones its receiving it from.
2792 snprintf(data,MAXBUF,"Y %d",time(NULL));
2793 serv->SendPacket(data,tcp_host);
2794 // send users and channels
2795 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2797 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);
2798 serv->SendPacket(data,tcp_host);
2799 if (strcmp(chlist(u->second),""))
2801 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2802 serv->SendPacket(data,tcp_host);
2805 // send channel modes, topics etc...
2806 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2808 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2809 serv->SendPacket(data,tcp_host);
2810 if (strcmp(c->second->topic,""))
2812 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2813 serv->SendPacket(data,tcp_host);
2815 // send current banlist
2817 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2819 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2820 serv->SendPacket(data,tcp_host);
2823 snprintf(data,MAXBUF,"F %d",time(NULL));
2824 serv->SendPacket(data,tcp_host);
2825 log(DEBUG,"Sent sync");
2826 // ircd sends its serverlist after the end of sync here
2830 void NetSendMyRoutingTable()
2832 // send out a line saying what is reachable to us.
2833 // E.g. if A is linked to B C and D, send out:
2835 // if its only linked to B and D send out:
2837 // if it has no links, dont even send out the line at all.
2838 char buffer[MAXBUF];
2839 sprintf(buffer,"$ %s",ServerName);
2840 bool sendit = false;
2841 for (int i = 0; i < 32; i++)
2845 for (int j = 0; j < me[i]->connectors.size(); j++)
2847 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
2849 strncat(buffer," ",MAXBUF);
2850 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2857 NetSendToAll(buffer);
2861 void DoSplit(const char* params)
2863 bool go_again = true;
2867 for (int i = 0; i < 32; i++)
2871 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2873 if (!strcasecmp(j->GetServerName().c_str(),params))
2876 j->CloseConnection();
2877 me[i]->connectors.erase(j);
2885 log(DEBUG,"Removed server. Will remove clients...");
2886 // iterate through the userlist and remove all users on this server.
2887 // because we're dealing with a mesh, we dont have to deal with anything
2888 // "down-route" from this server (nice huh)
2890 char reason[MAXBUF];
2891 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2895 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2897 if (!strcasecmp(u->second->server,params))
2899 kill_link(u->second,reason);
2907 // removes a server. Will NOT remove its users!
2909 void RemoveServer(const char* name)
2911 bool go_again = true;
2915 for (int i = 0; i < 32; i++)
2919 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2921 if (!strcasecmp(j->GetServerName().c_str(),name))
2924 j->CloseConnection();
2925 me[i]->connectors.erase(j);
2936 int reap_counter = 0;
2940 struct sockaddr_in client, server;
2941 char addrs[MAXBUF][255];
2942 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
2944 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
2945 int selectResult = 0, selectResult2 = 0;
2946 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2947 char resolvedHost[MAXBUF];
2951 log_file = fopen("ircd.log","a+");
2954 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
2958 log(DEBUG,"InspIRCd: startup: begin");
2962 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2964 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
2966 SetupCommandTable();
2967 log(DEBUG,"InspIRCd: startup: default command table set up");
2970 if (strcmp(DieValue,""))
2972 printf("WARNING: %s\n\n",DieValue);
2975 log(DEBUG,"InspIRCd: startup: read config");
2977 int count2 = 0, count3 = 0;
2979 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2981 ConfValue("bind","port",count,configToken,&config_f);
2982 ConfValue("bind","address",count,Addr,&config_f);
2983 ConfValue("bind","type",count,Type,&config_f);
2984 if (!strcmp(Type,"servers"))
2986 char Default[MAXBUF];
2987 strcpy(Default,"no");
2988 ConfValue("bind","default",count,Default,&config_f);
2989 if (strchr(Default,'y'))
2991 defaultRoute = count3;
2992 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2994 me[count3] = new serverrec(ServerName,100L,false);
2995 me[count3]->CreateListener(Addr,atoi(configToken));
3000 ports[count2] = atoi(configToken);
3001 strcpy(addrs[count2],Addr);
3004 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3007 UDPportCount = count3;
3009 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3011 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3015 /* BugFix By Craig! :p */
3017 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3019 char modfile[MAXBUF];
3020 ConfValue("module","name",count2,configToken,&config_f);
3021 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3022 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3023 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3024 /* If The File Doesnt exist, Trying to load it
3025 * Will Segfault the IRCd.. So, check to see if
3026 * it Exists, Before Proceeding. */
3027 if (FileExists(modfile))
3029 factory[count] = new ircd_module(modfile);
3030 if (factory[count]->LastError())
3032 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3033 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3036 if (factory[count]->factory)
3038 modules[count] = factory[count]->factory->CreateModule();
3039 /* save the module and the module's classfactory, if
3040 * this isnt done, random crashes can occur :/ */
3041 module_names.push_back(modfile);
3045 log(DEBUG,"Unable to load %s",modfile);
3046 sprintf("Unable to load %s\nExiting...\n",modfile);
3049 /* Increase the Count */
3054 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3055 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3058 MODCOUNT = count - 1;
3059 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3061 printf("\nInspIRCd is now running!\n");
3063 startup_time = time(NULL);
3067 log(VERBOSE,"Not forking as -nofork was specified");
3071 if (DaemonSeed() == ERROR)
3073 log(DEBUG,"InspIRCd: startup: can't daemonise");
3074 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3080 /* setup select call */
3081 FD_ZERO(&selectFds);
3082 log(DEBUG,"InspIRCd: startup: zero selects");
3083 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3085 for (count = 0; count < portCount; count++)
3087 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3089 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3092 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3094 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3096 else /* well we at least bound to one socket so we'll continue */
3102 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3104 /* if we didn't bind to anything then abort */
3105 if (boundPortCount == 0)
3107 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3112 length = sizeof (client);
3113 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3115 /* main loop, this never returns */
3118 #ifdef _POSIX_PRIORITY_SCHEDULING
3126 user_hash::iterator count2 = clientlist.begin();
3128 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3129 // them in a list, then reap the list every second or so.
3130 if (reap_counter>300)
3132 if (fd_reap.size() > 0)
3134 for( int n = 0; n < fd_reap.size(); n++)
3136 Blocking(fd_reap[n]);
3138 NonBlocking(fd_reap[n]);
3147 FD_ZERO(&serverfds);
3150 for (int x = 0; x != UDPportCount; x++)
3152 FD_SET(me[x]->fd, &serverfds);
3158 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3161 for (int x = 0; x != UDPportCount; x++)
3163 if (FD_ISSET (me[x]->fd, &serverfds))
3165 char remotehost[MAXBUF],resolved[MAXBUF];
3166 length = sizeof (client);
3167 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3168 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3169 if(CleanAndResolve(resolved, remotehost) != TRUE)
3171 strncpy(resolved,remotehost,MAXBUF);
3173 // add to this connections ircd_connector vector
3174 // *FIX* - we need the LOCAL port not the remote port in &client!
3175 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3180 for (int x = 0; x < UDPportCount; x++)
3182 std::deque<std::string> msgs;
3184 if (me[x]->RecvPacket(msgs, tcp_host))
3186 for (int ctr = 0; ctr < msgs.size(); ctr++)
3188 char udp_msg[MAXBUF];
3189 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3190 if (strlen(udp_msg)<1)
3192 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3195 // during a netburst, send all data to all other linked servers
3196 if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3198 NetSendToAllExcept(tcp_host,udp_msg);
3200 FOREACH_MOD OnPacketReceive(udp_msg);
3201 handle_link_packet(udp_msg, tcp_host, me[x]);
3208 while (count2 != clientlist.end())
3211 tval.tv_usec = tval.tv_sec = 0;
3213 int total_in_this_set = 0;
3215 user_hash::iterator xcount = count2;
3216 user_hash::iterator endingiter = count2;
3218 if (!count2->second) break;
3221 if (count2->second->fd != 0)
3223 // assemble up to 64 sockets into an fd_set
3224 // to implement a pooling mechanism.
3226 // This should be up to 64x faster than the
3227 // old implementation.
3228 while (total_in_this_set < 64)
3230 if (count2 != clientlist.end())
3232 // we don't check the state of remote users.
3233 if (count2->second->fd > 0)
3235 FD_SET (count2->second->fd, &sfd);
3237 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3238 // their connection class.
3239 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3241 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3242 kill_link(count2->second,"Registration timeout");
3245 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3247 if ((!count2->second->lastping) && (count2->second->registered == 7))
3249 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3250 kill_link(count2->second,"Ping timeout");
3253 Write(count2->second->fd,"PING :%s",ServerName);
3254 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3255 count2->second->lastping = 0;
3256 count2->second->nping = time(NULL)+120;
3260 total_in_this_set++;
3265 endingiter = count2;
3266 count2 = xcount; // roll back to where we were
3272 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3274 // now loop through all of the items in this pool if any are waiting
3275 //if (selectResult2 > 0)
3276 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3279 #ifdef _POSIX_PRIORITY_SCHEDULING
3284 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3286 log(DEBUG,"Reading fd %d",count2a->second->fd);
3287 memset(data, 0, 10240);
3288 result = read(count2a->second->fd, data, 10240);
3293 log(DEBUG,"Read %d characters from socket",result);
3294 userrec* current = count2a->second;
3295 int currfd = current->fd;
3296 char* l = strtok(data,"\n");
3301 if ((floodlines > current->flood) && (current->flood != 0))
3303 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3304 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3305 kill_link(current,"Excess flood");
3308 char sanitized[NetBufferSize];
3309 memset(sanitized, 0, NetBufferSize);
3311 for (int pt = 0; pt < strlen(l); pt++)
3315 sanitized[ptt++] = l[pt];
3318 sanitized[ptt] = '\0';
3319 if (strlen(sanitized))
3323 // we're gonna re-scan to check if the nick is gone, after every
3324 // command - if it has, we're gonna bail
3325 bool find_again = false;
3326 process_buffer(sanitized,current);
3328 // look for the user's record in case it's changed
3329 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3331 if (c2->second->fd == currfd)
3333 // found again, update pointer
3334 current == c2->second;
3343 l = strtok(NULL,"\n");
3348 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3350 log(DEBUG,"killing: %s",count2a->second->nick);
3351 kill_link(count2a->second,strerror(errno));
3355 // result EAGAIN means nothing read
3356 if (result == EAGAIN)
3364 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3365 kill_link(count2a->second,"Client exited");
3366 // must bail here? kill_link removes the hash, corrupting the iterator
3367 log(DEBUG,"Bailing from client exit");
3371 else if (result > 0)
3376 for (int q = 0; q < total_in_this_set; q++)
3378 // there is no iterator += operator :(
3379 //if (count2 != clientlist.end())
3386 // set up select call
3387 for (count = 0; count < boundPortCount; count++)
3389 FD_SET (openSockfd[count], &selectFds);
3393 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3395 /* select is reporting a waiting socket. Poll them all to find out which */
3396 if (selectResult > 0)
3398 char target[MAXBUF], resolved[MAXBUF];
3399 for (count = 0; count < boundPortCount; count++)
3401 if (FD_ISSET (openSockfd[count], &selectFds))
3403 length = sizeof (client);
3404 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3406 address_cache::iterator iter = IP.find(client.sin_addr);
3407 bool iscached = false;
3408 if (iter == IP.end())
3410 /* ip isn't in cache, add it */
3411 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3412 if(CleanAndResolve(resolved, target) != TRUE)
3414 strncpy(resolved,target,MAXBUF);
3416 /* hostname now in 'target' */
3417 IP[client.sin_addr] = new string(resolved);
3418 /* hostname in cache */
3422 /* found ip (cached) */
3423 strncpy(resolved, iter->second->c_str(), MAXBUF);
3427 if (incomingSockfd < 0)
3429 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3430 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3434 AddClient(incomingSockfd, resolved, ports[count], iscached);
3435 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3442 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3445 close (incomingSockfd);