1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
34 #include <ext/hash_map>
46 #include "connection.h"
60 #define nspace __gnu_cxx
65 int LogLevel = DEFAULT;
66 char ServerName[MAXBUF];
68 char ServerDesc[MAXBUF];
69 char AdminName[MAXBUF];
70 char AdminEmail[MAXBUF];
71 char AdminNick[MAXBUF];
73 char restartpass[MAXBUF];
77 char PrefixQuit[MAXBUF];
78 char DieValue[MAXBUF];
80 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
81 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
83 time_t startup_time = time(NULL);
84 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
85 extern int MaxWhoResults;
88 bool AllowHalfop = true;
89 bool AllowProtect = true;
90 bool AllowFounder = true;
92 extern std::vector<Module*> modules;
93 std::vector<std::string> module_names;
94 extern std::vector<ircd_module*> factory;
95 std::vector<int> fd_reap;
104 template<> struct hash<in_addr>
106 template<> struct nspace::hash<in_addr>
109 size_t operator()(const struct in_addr &a) const
112 memcpy(&q,&a,sizeof(size_t));
117 template<> struct hash<string>
119 template<> struct nspace::hash<string>
122 size_t operator()(const string &s) const
125 static struct hash<const char *> strhash;
126 strlcpy(a,s.c_str(),MAXBUF);
137 bool operator()(const string& s1, const string& s2) const
139 char a[MAXBUF],b[MAXBUF];
140 strlcpy(a,s1.c_str(),MAXBUF);
141 strlcpy(b,s2.c_str(),MAXBUF);
142 return (strcasecmp(a,b) == 0);
147 struct InAddr_HashComp
150 bool operator()(const in_addr &s1, const in_addr &s2) const
155 memcpy(&q,&s1,sizeof(size_t));
156 memcpy(&p,&s2,sizeof(size_t));
164 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
165 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
166 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
167 typedef std::deque<command_t> command_table;
173 user_hash clientlist;
176 command_table cmdlist;
183 struct linger linger = { 0 };
184 char MyExecutable[1024];
185 int boundPortCount = 0;
186 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
187 int defaultRoute = 0;
191 long MyKey = C.GenKey();
195 int has_channel(userrec *u, chanrec *c);
196 int usercount(chanrec *c);
197 int usercount_i(chanrec *c);
198 void update_stats_l(int fd,int data_out);
199 char* Passwd(userrec *user);
200 bool IsDenied(userrec *user);
201 void AddWhoWas(userrec* u);
203 std::vector<long> auth_cookies;
204 std::stringstream config_f(stringstream::in | stringstream::out);
210 char Revision[] = "$Revision$";
213 char *v1 = strtok_r(s1," ",&savept);
215 char *v2 = strtok_r(s1," ",&savept);
217 return (long)(atof(v2)*10000);
221 std::string getservername()
226 std::string getserverdesc()
231 std::string getnetworkname()
236 std::string getadminname()
241 std::string getadminemail()
246 std::string getadminnick()
251 void log(int level,char *text, ...)
253 char textbuffer[MAXBUF];
256 struct tm * timeinfo;
257 if (level < LogLevel)
261 timeinfo = localtime (&rawtime);
266 va_start (argsPtr, text);
267 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
269 strlcpy(b,asctime(timeinfo),MAXBUF);
270 b[strlen(b)-1] = ':';
271 fprintf(log_file,"%s %s\n",b,textbuffer);
274 // nofork enabled? display it on terminal too
275 printf("%s %s\n",b,textbuffer);
280 void readfile(file_cache &F, const char* fname)
283 char linebuf[MAXBUF];
285 log(DEBUG,"readfile: loading %s",fname);
287 file = fopen(fname,"r");
292 fgets(linebuf,sizeof(linebuf),file);
293 linebuf[strlen(linebuf)-1]='\0';
294 if (!strcmp(linebuf,""))
300 F.push_back(linebuf);
307 log(DEBUG,"readfile: failed to load file: %s",fname);
309 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
312 void ReadConfig(bool bail, userrec* user)
314 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
315 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF];
317 std::stringstream errstr;
319 if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
324 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
332 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
333 while (!errstr.eof())
335 errstr.getline(dataline,1024);
336 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
341 WriteOpers("There were errors in the configuration file:",user->nick);
342 while (!errstr.eof())
344 errstr.getline(dataline,1024);
345 WriteOpers(dataline);
352 ConfValue("server","name",0,ServerName,&config_f);
353 ConfValue("server","description",0,ServerDesc,&config_f);
354 ConfValue("server","network",0,Network,&config_f);
355 ConfValue("admin","name",0,AdminName,&config_f);
356 ConfValue("admin","email",0,AdminEmail,&config_f);
357 ConfValue("admin","nick",0,AdminNick,&config_f);
358 ConfValue("files","motd",0,motd,&config_f);
359 ConfValue("files","rules",0,rules,&config_f);
360 ConfValue("power","diepass",0,diepass,&config_f);
361 ConfValue("power","pause",0,pauseval,&config_f);
362 ConfValue("power","restartpass",0,restartpass,&config_f);
363 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
364 ConfValue("die","value",0,DieValue,&config_f);
365 ConfValue("options","loglevel",0,dbg,&config_f);
366 ConfValue("options","netbuffersize",0,NB,&config_f);
367 ConfValue("options","maxwho",0,MW,&config_f);
368 ConfValue("options","allowhalfop",0,AH,&config_f);
369 ConfValue("options","allowprotect",0,AP,&config_f);
370 ConfValue("options","allowfounder",0,AF,&config_f);
371 NetBufferSize = atoi(NB);
372 MaxWhoResults = atoi(MW);
373 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
374 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
375 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
376 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
378 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
379 NetBufferSize = 10240;
381 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
383 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
386 if (!strcmp(dbg,"debug"))
388 if (!strcmp(dbg,"verbose"))
390 if (!strcmp(dbg,"default"))
392 if (!strcmp(dbg,"sparse"))
394 if (!strcmp(dbg,"none"))
397 log(DEFAULT,"Reading message of the day...");
398 readfile(RULES,rules);
399 log(DEFAULT,"Reading connect classes...");
401 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
404 ConfValue("connect","allow",i,Value,&config_f);
405 ConfValue("connect","timeout",i,timeout,&config_f);
406 ConfValue("connect","flood",i,flood,&config_f);
407 if (strcmp(Value,""))
409 strlcpy(c.host,Value,MAXBUF);
411 strlcpy(Value,"",MAXBUF);
412 ConfValue("connect","password",i,Value,&config_f);
413 strlcpy(c.pass,Value,MAXBUF);
414 c.registration_timeout = 90; // default is 2 minutes
415 c.flood = atoi(flood);
418 c.registration_timeout = atoi(timeout);
420 Classes.push_back(c);
421 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
425 ConfValue("connect","deny",i,Value,&config_f);
426 strlcpy(c.host,Value,MAXBUF);
428 Classes.push_back(c);
429 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
433 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
434 read_xline_defaults();
435 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
437 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
440 /* write formatted text to a socket, in same format as printf */
442 void Write(int sock,char *text, ...)
446 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
449 char textbuffer[MAXBUF];
453 va_start (argsPtr, text);
454 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
456 snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
460 write(sock,tb,strlen(tb));
461 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
465 /* write a server formatted numeric response to a single socket */
467 void WriteServ(int sock, char* text, ...)
471 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
474 char textbuffer[MAXBUF],tb[MAXBUF];
476 va_start (argsPtr, text);
478 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
480 snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
484 write(sock,tb,strlen(tb));
485 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
489 /* write text from an originating user to originating user */
491 void WriteFrom(int sock, userrec *user,char* text, ...)
493 if ((!text) || (!user))
495 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
498 char textbuffer[MAXBUF],tb[MAXBUF];
500 va_start (argsPtr, text);
502 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
504 snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
508 write(sock,tb,strlen(tb));
509 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
513 /* write text to an destination user from a source user (e.g. user privmsg) */
515 void WriteTo(userrec *source, userrec *dest,char *data, ...)
517 if ((!dest) || (!data))
519 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
522 char textbuffer[MAXBUF],tb[MAXBUF];
524 va_start (argsPtr, data);
525 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
529 // if no source given send it from the server.
532 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
536 WriteFrom(dest->fd,source,"%s",textbuffer);
540 /* write formatted text from a source user to all users on a channel
541 * including the sender (NOT for privmsg, notice etc!) */
543 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
545 if ((!Ptr) || (!user) || (!text))
547 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
550 char textbuffer[MAXBUF];
552 va_start (argsPtr, text);
553 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
555 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
557 if (has_channel(i->second,Ptr))
559 WriteTo(user,i->second,"%s",textbuffer);
564 /* write formatted text from a source user to all users on a channel
565 * including the sender (NOT for privmsg, notice etc!) doesnt send to
566 * users on remote servers */
568 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
570 if ((!Ptr) || (!text))
572 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
575 char textbuffer[MAXBUF];
577 va_start (argsPtr, text);
578 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
580 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
582 if (has_channel(i->second,Ptr))
584 if (i->second->fd != -1)
588 WriteServ(i->second->fd,"%s",textbuffer);
592 WriteTo(user,i->second,"%s",textbuffer);
600 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
602 if ((!Ptr) || (!user) || (!text))
604 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
607 char textbuffer[MAXBUF];
609 va_start (argsPtr, text);
610 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
612 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
616 if (has_channel(i->second,Ptr))
618 WriteServ(i->second->fd,"%s",textbuffer);
625 /* write formatted text from a source user to all users on a channel except
626 * for the sender (for privmsg etc) */
628 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
630 if ((!Ptr) || (!user) || (!text))
632 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
635 char textbuffer[MAXBUF];
637 va_start (argsPtr, text);
638 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
641 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
645 if (has_channel(i->second,Ptr) && (user != i->second))
647 WriteTo(user,i->second,"%s",textbuffer);
654 std::string GetServerDescription(char* servername)
656 for (int j = 0; j < 32; j++)
660 for (int k = 0; k < me[j]->connectors.size(); k++)
662 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
664 return me[j]->connectors[k].GetDescription();
668 return ServerDesc; // not a remote server that can be found, it must be me.
673 /* write a formatted string to all users who share at least one common
674 * channel, including the source user e.g. for use in NICK */
676 void WriteCommon(userrec *u, char* text, ...)
680 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
684 if (u->registered != 7) {
685 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
689 char textbuffer[MAXBUF];
691 va_start (argsPtr, text);
692 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
695 WriteFrom(u->fd,u,"%s",textbuffer);
697 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
701 if (common_channels(u,i->second) && (i->second != u))
703 WriteFrom(i->second->fd,u,"%s",textbuffer);
709 /* write a formatted string to all users who share at least one common
710 * channel, NOT including the source user e.g. for use in QUIT */
712 void WriteCommonExcept(userrec *u, char* text, ...)
716 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
720 if (u->registered != 7) {
721 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
725 char textbuffer[MAXBUF];
727 va_start (argsPtr, text);
728 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
731 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
735 if ((common_channels(u,i->second)) && (u != i->second))
737 WriteFrom(i->second->fd,u,"%s",textbuffer);
743 void WriteOpers(char* text, ...)
747 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
751 char textbuffer[MAXBUF];
753 va_start (argsPtr, text);
754 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
757 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
761 if (strchr(i->second->modes,'o'))
763 if (strchr(i->second->modes,'s'))
765 // send server notices to all with +s
766 // (TODO: needs SNOMASKs)
767 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
774 // returns TRUE of any users on channel C occupy server 'servername'.
776 bool ChanAnyOnThisServer(chanrec *c,char* servername)
778 log(DEBUG,"ChanAnyOnThisServer");
779 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
781 if (has_channel(i->second,c))
783 if (!strcasecmp(i->second->server,servername))
792 // returns true if user 'u' shares any common channels with any users on server 'servername'
794 bool CommonOnThisServer(userrec* u,const char* servername)
796 log(DEBUG,"ChanAnyOnThisServer");
797 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
799 if ((common_channels(u,i->second)) && (u != i->second))
801 if (!strcasecmp(i->second->server,servername))
803 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
812 void NetSendToCommon(userrec* u, char* s)
815 snprintf(buffer,MAXBUF,"%s",s);
817 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
819 for (int j = 0; j < 32; j++)
823 for (int k = 0; k < me[j]->connectors.size(); k++)
825 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
827 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
835 void NetSendToAll(char* s)
838 snprintf(buffer,MAXBUF,"%s",s);
840 log(DEBUG,"NetSendToAll: '%s'",s);
842 for (int j = 0; j < 32; j++)
846 for (int k = 0; k < me[j]->connectors.size(); k++)
848 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
854 void NetSendToAllAlive(char* s)
857 snprintf(buffer,MAXBUF,"%s",s);
859 log(DEBUG,"NetSendToAllAlive: '%s'",s);
861 for (int j = 0; j < 32; j++)
865 for (int k = 0; k < me[j]->connectors.size(); k++)
867 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
869 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
873 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
881 void NetSendToOne(char* target,char* s)
884 snprintf(buffer,MAXBUF,"%s",s);
886 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
888 for (int j = 0; j < 32; j++)
892 for (int k = 0; k < me[j]->connectors.size(); k++)
894 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
896 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
903 void NetSendToAllExcept(const char* target,char* s)
906 snprintf(buffer,MAXBUF,"%s",s);
908 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
910 for (int j = 0; j < 32; j++)
914 for (int k = 0; k < me[j]->connectors.size(); k++)
916 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
918 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
926 void WriteMode(const char* modes, int flags, const char* text, ...)
928 if ((!text) || (!modes) || (!flags))
930 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
934 char textbuffer[MAXBUF];
936 va_start (argsPtr, text);
937 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
940 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
944 bool send_to_user = false;
949 for (int n = 0; n < strlen(modes); n++)
951 if (!hasumode(i->second,modes[n]))
953 send_to_user = false;
958 else if (flags == WM_OR)
960 send_to_user = false;
961 for (int n = 0; n < strlen(modes); n++)
963 if (hasumode(i->second,modes[n]))
973 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
980 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
982 if ((!text) || (!source))
984 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
989 char textbuffer[MAXBUF];
991 va_start (argsPtr, text);
992 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
995 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
999 if (strchr(i->second->modes,'w'))
1001 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1008 char buffer[MAXBUF];
1009 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1010 NetSendToAll(buffer);
1014 /* convert a string to lowercase. Note following special circumstances
1015 * taken from RFC 1459. Many "official" server branches still hold to this
1016 * rule so i will too;
1018 * Because of IRC's scandanavian origin, the characters {}| are
1019 * considered to be the lower case equivalents of the characters []\,
1020 * respectively. This is a critical issue when determining the
1021 * equivalence of two nicknames.
1024 void strlower(char *n)
1030 for (int i = 0; i != strlen(n); i++)
1032 n[i] = tolower(n[i]);
1044 /* Find a user record by nickname and return a pointer to it */
1046 userrec* Find(string nick)
1048 user_hash::iterator iter = clientlist.find(nick);
1050 if (iter == clientlist.end())
1051 /* Couldn't find it */
1054 return iter->second;
1057 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1059 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1063 if (i->second->fd == fd)
1065 i->second->bytes_out+=data_out;
1066 i->second->cmds_out++;
1073 /* find a channel record by channel name and return a pointer to it */
1075 chanrec* FindChan(const char* chan)
1079 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1083 chan_hash::iterator iter = chanlist.find(chan);
1085 if (iter == chanlist.end())
1086 /* Couldn't find it */
1089 return iter->second;
1093 void purge_empty_chans(void)
1095 int go_again = 1, purge = 0;
1100 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1103 if (!usercount(i->second))
1105 /* kill the record */
1106 if (i != chanlist.end())
1108 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1118 log(DEBUG,"skipped purge for %s",i->second->name);
1123 log(DEBUG,"completed channel purge, killed %d",purge);
1127 char scratch[MAXBUF];
1128 char sparam[MAXBUF];
1130 char* chanmodes(chanrec *chan)
1134 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1141 if (chan->noexternal)
1143 strlcat(scratch,"n",MAXMODES);
1145 if (chan->topiclock)
1147 strlcat(scratch,"t",MAXMODES);
1149 if (strcmp(chan->key,""))
1151 strlcat(scratch,"k",MAXMODES);
1155 strlcat(scratch,"l",MAXMODES);
1157 if (chan->inviteonly)
1159 strlcat(scratch,"i",MAXMODES);
1161 if (chan->moderated)
1163 strlcat(scratch,"m",MAXMODES);
1167 strlcat(scratch,"s",MAXMODES);
1169 if (chan->c_private)
1171 strlcat(scratch,"p",MAXMODES);
1173 if (strcmp(chan->key,""))
1175 strlcat(sparam," ",MAXBUF);
1176 strlcat(sparam,chan->key,MAXBUF);
1181 sprintf(foo," %d",chan->limit);
1182 strlcat(sparam,foo,MAXBUF);
1184 if (strlen(chan->custom_modes))
1186 strlcat(scratch,chan->custom_modes,MAXMODES);
1187 for (int z = 0; z < strlen(chan->custom_modes); z++)
1189 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1192 strlcat(sparam," ",MAXBUF);
1193 strlcat(sparam,extparam.c_str(),MAXBUF);
1197 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1198 strlcat(scratch,sparam,MAXMODES);
1203 /* compile a userlist of a channel into a string, each nick seperated by
1204 * spaces and op, voice etc status shown as @ and + */
1206 void userlist(userrec *user,chanrec *c)
1208 if ((!c) || (!user))
1210 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1214 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1215 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1217 if (has_channel(i->second,c))
1219 if (isnick(i->second->nick))
1221 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1223 /* user is +i, and source not on the channel, does not show
1224 * nick in NAMES list */
1227 strlcat(list,cmode(i->second,c),MAXBUF);
1228 strlcat(list,i->second->nick,MAXBUF);
1229 strlcat(list," ",MAXBUF);
1230 if (strlen(list)>(480-NICKMAX))
1232 /* list overflowed into
1233 * multiple numerics */
1234 WriteServ(user->fd,list);
1235 snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1240 /* if whats left in the list isnt empty, send it */ if (list[strlen(list)-1] != ':')
1242 WriteServ(user->fd,list);
1246 /* return a count of the users on a specific channel accounting for
1247 * invisible users who won't increase the count. e.g. for /LIST */
1249 int usercount_i(chanrec *c)
1256 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1261 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1265 if (has_channel(i->second,c))
1267 if (isnick(i->second->nick))
1269 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1271 /* user is +i, and source not on the channel, does not show
1272 * nick in NAMES list */
1280 log(DEBUG,"usercount_i: %s %d",c->name,count);
1285 int usercount(chanrec *c)
1292 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1297 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1301 if (has_channel(i->second,c))
1303 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1310 log(DEBUG,"usercount: %s %d",c->name,count);
1315 /* add a channel to a user, creating the record for it if needed and linking
1316 * it to the user record */
1318 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1320 if ((!user) || (!cn))
1322 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1331 strncpy(cname,cn,MAXBUF);
1333 // we MUST declare this wherever we use FOREACH_RESULT
1336 if (strlen(cname) > CHANMAX-1)
1338 cname[CHANMAX-1] = '\0';
1341 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1343 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1345 return NULL; // already on the channel!
1349 if (!FindChan(cname))
1352 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1353 if (MOD_RESULT == 1) {
1357 /* create a new one */
1358 log(DEBUG,"add_channel: creating: %s",cname);
1360 chanlist[cname] = new chanrec();
1362 strlcpy(chanlist[cname]->name, cname,CHANMAX);
1363 chanlist[cname]->topiclock = 1;
1364 chanlist[cname]->noexternal = 1;
1365 chanlist[cname]->created = time(NULL);
1366 strcpy(chanlist[cname]->topic, "");
1367 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1368 chanlist[cname]->topicset = 0;
1369 Ptr = chanlist[cname];
1370 log(DEBUG,"add_channel: created: %s",cname);
1371 /* set created to 2 to indicate user
1372 * is the first in the channel
1373 * and should be given ops */
1379 /* channel exists, just fish out a pointer to its struct */
1380 Ptr = FindChan(cname);
1383 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1385 // the override flag allows us to bypass channel modes
1386 // and bans (used by servers)
1390 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1391 if (MOD_RESULT == 1) {
1395 if (MOD_RESULT == 0)
1398 if (strcmp(Ptr->key,""))
1400 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1403 log(DEBUG,"add_channel: no key given in JOIN");
1404 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1409 log(DEBUG,"key at %p is %s",key,key);
1410 if (strcasecmp(key,Ptr->key))
1412 log(DEBUG,"add_channel: bad key given in JOIN");
1413 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1418 log(DEBUG,"add_channel: no key");
1420 if (Ptr->inviteonly)
1422 log(DEBUG,"add_channel: channel is +i");
1423 if (user->IsInvited(Ptr->name))
1425 /* user was invited to channel */
1426 /* there may be an optional channel NOTICE here */
1430 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1434 log(DEBUG,"add_channel: channel is not +i");
1438 if (usercount(Ptr) == Ptr->limit)
1440 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1445 log(DEBUG,"add_channel: about to walk banlist");
1447 /* check user against the channel banlist */
1450 if (Ptr->bans.size())
1452 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1454 if (match(user->GetFullHost(),i->data))
1456 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1463 log(DEBUG,"add_channel: bans checked");
1468 if ((Ptr) && (user))
1470 user->RemoveInvite(Ptr->name);
1473 log(DEBUG,"add_channel: invites removed");
1478 log(DEBUG,"Overridden checks");
1486 log(DEBUG,"Passed channel checks");
1488 for (int i =0; i != MAXCHANS; i++)
1490 log(DEBUG,"Check location %d",i);
1491 if (user->chans[i].channel == NULL)
1493 log(DEBUG,"Adding into their channel list at location %d",i);
1497 /* first user in is given ops */
1498 user->chans[i].uc_modes = UCMODE_OP;
1502 user->chans[i].uc_modes = 0;
1504 user->chans[i].channel = Ptr;
1505 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1507 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1509 // use the stamdard J token with no privilages.
1510 char buffer[MAXBUF];
1513 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1517 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1519 NetSendToAll(buffer);
1522 log(DEBUG,"Sent JOIN to client");
1526 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1527 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1530 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1531 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1532 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1533 FOREACH_MOD OnUserJoin(user,Ptr);
1537 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1538 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1542 /* remove a channel from a users record, and remove the record from memory
1543 * if the channel has become empty */
1545 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1547 if ((!user) || (!cname))
1549 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1556 if ((!cname) || (!user))
1561 Ptr = FindChan(cname);
1568 FOREACH_MOD OnUserPart(user,Ptr);
1569 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1571 for (int i =0; i != MAXCHANS; i++)
1573 /* zap it from the channel list of the user */
1574 if (user->chans[i].channel == Ptr)
1578 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1582 char buffer[MAXBUF];
1583 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1584 NetSendToAll(buffer);
1593 char buffer[MAXBUF];
1594 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1595 NetSendToAll(buffer);
1598 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1600 user->chans[i].uc_modes = 0;
1601 user->chans[i].channel = NULL;
1602 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1607 /* if there are no users left on the channel */
1608 if (!usercount(Ptr))
1610 chan_hash::iterator iter = chanlist.find(Ptr->name);
1612 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1614 /* kill the record */
1615 if (iter != chanlist.end())
1617 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1618 delete iter->second;
1619 chanlist.erase(iter);
1625 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1627 if ((!src) || (!user) || (!Ptr) || (!reason))
1629 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1636 if ((!Ptr) || (!user) || (!src))
1641 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1643 if (!has_channel(user,Ptr))
1645 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1650 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1652 if (MOD_RESULT == ACR_DENY)
1655 if (MOD_RESULT == ACR_DEFAULT)
1657 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1659 if (cstatus(src,Ptr) == STATUS_HOP)
1661 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1665 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1672 for (int i =0; i != MAXCHANS; i++)
1674 /* zap it from the channel list of the user */
1675 if (user->chans[i].channel)
1676 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1678 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1679 user->chans[i].uc_modes = 0;
1680 user->chans[i].channel = NULL;
1681 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1686 /* if there are no users left on the channel */
1687 if (!usercount(Ptr))
1689 chan_hash::iterator iter = chanlist.find(Ptr->name);
1691 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1693 /* kill the record */
1694 if (iter != chanlist.end())
1696 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1697 delete iter->second;
1698 chanlist.erase(iter);
1706 /* This function pokes and hacks at a parameter list like the following:
1708 * PART #winbot, #darkgalaxy :m00!
1710 * to turn it into a series of individual calls like this:
1712 * PART #winbot :m00!
1713 * PART #darkgalaxy :m00!
1715 * The seperate calls are sent to a callback function provided by the caller
1716 * (the caller will usually call itself recursively). The callback function
1717 * must be a command handler. Calling this function on a line with no list causes
1718 * no action to be taken. You must provide a starting and ending parameter number
1719 * where the range of the list can be found, useful if you have a terminating
1720 * parameter as above which is actually not part of the list, or parameters
1721 * before the actual list as well. This code is used by many functions which
1722 * can function as "one to list" (see the RFC) */
1724 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1729 char blog[32][MAXBUF];
1730 char blog2[32][MAXBUF];
1731 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1732 char keystr[MAXBUF];
1735 for (int i = 0; i <32; i++)
1738 for (int i = 0; i <32; i++)
1739 strcpy(blog2[i],"");
1742 for (int i = 0; i <10; i++)
1746 parameters[i] = moo;
1751 if (pcnt > 1) /* we have a key to copy */
1753 strlcpy(keystr,parameters[1],MAXBUF);
1757 if (!parameters[start])
1761 if (!strchr(parameters[start],','))
1766 for (int i = start; i <= end; i++)
1770 strlcat(plist,parameters[i],MAXBUF);
1778 for (int i = 0; i < t; i++)
1780 if (plist[i] == ',')
1783 strlcpy(blog[j++],param,MAXBUF);
1787 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1792 strlcpy(blog[j++],param,MAXBUF);
1795 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1800 if ((joins) && (keystr))
1802 if (strchr(keystr,','))
1806 t2 = strlen(keystr);
1807 for (int i = 0; i < t2; i++)
1809 if (keystr[i] == ',')
1812 strlcpy(blog2[j++],param,MAXBUF);
1816 strlcpy(blog2[j++],param,MAXBUF);
1821 for (j = 0; j < total; j++)
1827 for (q = end; q < pcnt-1; q++)
1829 if (parameters[q+1])
1831 pars[q-end+1] = parameters[q+1];
1834 if ((joins) && (parameters[1]))
1845 /* repeatedly call the function with the hacked parameter list */
1846 if ((joins) && (pcnt > 1))
1850 // pars[1] already set up and containing key from blog2[j]
1855 pars[1] = parameters[1];
1861 fn(pars,pcnt-(end-start),u);
1870 void kill_link(userrec *user,const char* r)
1872 user_hash::iterator iter = clientlist.find(user->nick);
1874 char reason[MAXBUF];
1876 strncpy(reason,r,MAXBUF);
1878 if (strlen(reason)>MAXQUIT)
1880 reason[MAXQUIT-1] = '\0';
1883 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1884 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1885 log(DEBUG,"closing fd %d",user->fd);
1887 /* bugfix, cant close() a nonblocking socket (sux!) */
1888 if (user->registered == 7) {
1889 FOREACH_MOD OnUserQuit(user);
1890 WriteCommonExcept(user,"QUIT :%s",reason);
1892 // Q token must go to ALL servers!!!
1893 char buffer[MAXBUF];
1894 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1895 NetSendToAll(buffer);
1898 /* push the socket on a stack of sockets due to be closed at the next opportunity
1899 * 'Client exited' is an exception to this as it means the client side has already
1900 * closed the socket, we don't need to do it.
1902 fd_reap.push_back(user->fd);
1904 bool do_purge = false;
1906 if (user->registered == 7) {
1907 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1911 if (iter != clientlist.end())
1913 log(DEBUG,"deleting user hash value %d",iter->second);
1914 if ((iter->second) && (user->registered == 7)) {
1915 delete iter->second;
1917 clientlist.erase(iter);
1920 if (user->registered == 7) {
1921 purge_empty_chans();
1925 void kill_link_silent(userrec *user,const char* r)
1927 user_hash::iterator iter = clientlist.find(user->nick);
1929 char reason[MAXBUF];
1931 strncpy(reason,r,MAXBUF);
1933 if (strlen(reason)>MAXQUIT)
1935 reason[MAXQUIT-1] = '\0';
1938 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1939 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1940 log(DEBUG,"closing fd %d",user->fd);
1942 /* bugfix, cant close() a nonblocking socket (sux!) */
1943 if (user->registered == 7) {
1944 FOREACH_MOD OnUserQuit(user);
1945 WriteCommonExcept(user,"QUIT :%s",reason);
1947 // Q token must go to ALL servers!!!
1948 char buffer[MAXBUF];
1949 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1950 NetSendToAll(buffer);
1953 /* push the socket on a stack of sockets due to be closed at the next opportunity
1954 * 'Client exited' is an exception to this as it means the client side has already
1955 * closed the socket, we don't need to do it.
1957 fd_reap.push_back(user->fd);
1959 bool do_purge = false;
1961 if (iter != clientlist.end())
1963 log(DEBUG,"deleting user hash value %d",iter->second);
1964 if ((iter->second) && (user->registered == 7)) {
1965 delete iter->second;
1967 clientlist.erase(iter);
1970 if (user->registered == 7) {
1971 purge_empty_chans();
1977 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1979 char* Passwd(userrec *user)
1981 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1983 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1991 bool IsDenied(userrec *user)
1993 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1995 if (match(user->host,i->host) && (i->type == CC_DENY))
2006 /* sends out an error notice to all connected clients (not to be used
2009 void send_error(char *s)
2011 log(DEBUG,"send_error: %s",s);
2012 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2014 if (isnick(i->second->nick))
2016 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2020 // fix - unregistered connections receive ERROR, not NOTICE
2021 Write(i->second->fd,"ERROR :%s",s);
2026 void Error(int status)
2028 signal (SIGALRM, SIG_IGN);
2029 signal (SIGPIPE, SIG_IGN);
2030 signal (SIGTERM, SIG_IGN);
2031 signal (SIGABRT, SIG_IGN);
2032 signal (SIGSEGV, SIG_IGN);
2033 signal (SIGURG, SIG_IGN);
2034 signal (SIGKILL, SIG_IGN);
2035 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2036 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2041 int main(int argc, char **argv)
2045 log(DEBUG,"*** InspIRCd starting up!");
2046 if (!FileExists(CONFIG_FILE))
2048 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2049 log(DEBUG,"main: no config");
2050 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2054 for (int i = 1; i < argc; i++)
2056 if (!strcmp(argv[i],"-nofork")) {
2059 if (!strcmp(argv[i],"-wait")) {
2064 strlcpy(MyExecutable,argv[0],MAXBUF);
2066 if (InspIRCd() == ERROR)
2068 log(DEBUG,"main: daemon function bailed");
2069 printf("ERROR: could not initialise. Shutting down.\n");
2076 template<typename T> inline string ConvToStr(const T &in)
2079 if (!(tmp << in)) return string();
2083 /* re-allocates a nick in the user_hash after they change nicknames,
2084 * returns a pointer to the new user as it may have moved */
2086 userrec* ReHashNick(char* Old, char* New)
2088 user_hash::iterator newnick;
2089 user_hash::iterator oldnick = clientlist.find(Old);
2091 log(DEBUG,"ReHashNick: %s %s",Old,New);
2093 if (!strcasecmp(Old,New))
2095 log(DEBUG,"old nick is new nick, skipping");
2096 return oldnick->second;
2099 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2101 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2103 clientlist[New] = new userrec();
2104 clientlist[New] = oldnick->second;
2105 /*delete oldnick->second; */
2106 clientlist.erase(oldnick);
2108 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2110 return clientlist[New];
2113 /* adds or updates an entry in the whowas list */
2114 void AddWhoWas(userrec* u)
2116 user_hash::iterator iter = whowas.find(u->nick);
2117 userrec *a = new userrec();
2118 strlcpy(a->nick,u->nick,NICKMAX);
2119 strlcpy(a->ident,u->ident,64);
2120 strlcpy(a->dhost,u->dhost,256);
2121 strlcpy(a->host,u->host,256);
2122 strlcpy(a->fullname,u->fullname,128);
2123 strlcpy(a->server,u->server,256);
2124 a->signon = u->signon;
2126 /* MAX_WHOWAS: max number of /WHOWAS items
2127 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2128 * can be replaced by a newer one
2131 if (iter == whowas.end())
2133 if (whowas.size() == WHOWAS_MAX)
2135 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2137 // 3600 seconds in an hour ;)
2138 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2142 log(DEBUG,"added WHOWAS entry, purged an old record");
2149 log(DEBUG,"added fresh WHOWAS entry");
2150 whowas[a->nick] = a;
2155 log(DEBUG,"updated WHOWAS entry");
2156 delete iter->second;
2162 /* add a client connection to the sockets list */
2163 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2167 char resolved[MAXBUF];
2170 user_hash::iterator iter;
2172 tempnick = ConvToStr(socket) + "-unknown";
2173 sprintf(tn2,"%d-unknown",socket);
2175 iter = clientlist.find(tempnick);
2177 if (iter != clientlist.end()) return;
2180 * It is OK to access the value here this way since we know
2181 * it exists, we just created it above.
2183 * At NO other time should you access a value in a map or a
2184 * hash_map this way.
2186 clientlist[tempnick] = new userrec();
2188 NonBlocking(socket);
2189 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2191 clientlist[tempnick]->fd = socket;
2192 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2193 strncpy(clientlist[tempnick]->host, host,160);
2194 strncpy(clientlist[tempnick]->dhost, host,160);
2195 strncpy(clientlist[tempnick]->server, ServerName,256);
2196 strncpy(clientlist[tempnick]->ident, "unknown",9);
2197 clientlist[tempnick]->registered = 0;
2198 clientlist[tempnick]->signon = time(NULL);
2199 clientlist[tempnick]->nping = time(NULL)+240;
2200 clientlist[tempnick]->lastping = 1;
2201 clientlist[tempnick]->port = port;
2202 strncpy(clientlist[tempnick]->ip,ip,32);
2206 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2210 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2213 // set the registration timeout for this user
2214 unsigned long class_regtimeout = 90;
2215 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2217 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2219 class_regtimeout = (unsigned long)i->registration_timeout;
2224 int class_flood = 0;
2225 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2227 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2229 class_flood = i->flood;
2234 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2235 clientlist[tempnick]->flood = class_flood;
2237 for (int i = 0; i < MAXCHANS; i++)
2239 clientlist[tempnick]->chans[i].channel = NULL;
2240 clientlist[tempnick]->chans[i].uc_modes = 0;
2243 if (clientlist.size() == MAXCLIENTS)
2244 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2246 char* r = matches_zline(ip);
2249 char reason[MAXBUF];
2250 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2251 kill_link(clientlist[tempnick],reason);
2258 return clientlist.size();
2262 int usercount_invisible(void)
2266 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2268 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2273 int usercount_opers(void)
2277 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2279 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2284 int usercount_unknown(void)
2288 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2290 if ((i->second->fd) && (i->second->registered != 7))
2296 long chancount(void)
2298 return chanlist.size();
2301 long count_servs(void)
2304 //for (int j = 0; j < 255; j++)
2306 // if (servers[j] != NULL)
2312 long servercount(void)
2314 return count_servs()+1;
2320 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2322 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2328 void ShowMOTD(userrec *user)
2332 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2335 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2336 for (int i = 0; i != MOTD.size(); i++)
2338 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2340 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2343 void ShowRULES(userrec *user)
2347 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2350 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2351 for (int i = 0; i != RULES.size(); i++)
2353 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2355 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2358 /* shows the message of the day, and any other on-logon stuff */
2359 void ConnectUser(userrec *user)
2361 user->registered = 7;
2362 user->idle_lastmsg = time(NULL);
2363 log(DEBUG,"ConnectUser: %s",user->nick);
2365 if (strcmp(Passwd(user),"") && (!user->haspassed))
2367 kill_link(user,"Invalid password");
2372 kill_link(user,"Unauthorised connection");
2376 char match_against[MAXBUF];
2377 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2378 char* r = matches_gline(match_against);
2381 char reason[MAXBUF];
2382 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2383 kill_link_silent(user,reason);
2387 r = matches_kline(user->host);
2390 char reason[MAXBUF];
2391 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2392 kill_link_silent(user,reason);
2396 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2397 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2398 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2399 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2400 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2401 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);
2402 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);
2404 FOREACH_MOD OnUserConnect(user);
2405 WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2407 char buffer[MAXBUF];
2408 snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2409 NetSendToAll(buffer);
2412 void handle_version(char **parameters, int pcnt, userrec *user)
2414 char Revision[] = "$Revision$";
2416 char *s1 = Revision;
2418 char *v1 = strtok_r(s1," ",&savept);
2420 char *v2 = strtok_r(s1," ",&savept);
2423 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2427 // calls a handler function for a command
2429 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2431 for (int i = 0; i < cmdlist.size(); i++)
2433 if (!strcasecmp(cmdlist[i].command,commandname))
2435 if (cmdlist[i].handler_function)
2437 if (pcnt>=cmdlist[i].min_params)
2439 if (strchr(user->modes,cmdlist[i].flags_needed))
2441 cmdlist[i].handler_function(parameters,pcnt,user);
2449 void DoSplitEveryone()
2451 bool go_again = true;
2455 for (int i = 0; i < 32; i++)
2459 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2461 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2464 j->CloseConnection();
2465 me[i]->connectors.erase(j);
2473 log(DEBUG,"Removed server. Will remove clients...");
2474 // iterate through the userlist and remove all users on this server.
2475 // because we're dealing with a mesh, we dont have to deal with anything
2476 // "down-route" from this server (nice huh)
2478 char reason[MAXBUF];
2482 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2484 if (strcasecmp(u->second->server,ServerName))
2486 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2487 kill_link(u->second,reason);
2497 char islast(const char* s)
2500 for (int j = 0; j < 32; j++)
2504 for (int k = 0; k < me[j]->connectors.size(); k++)
2506 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2510 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2520 long map_count(const char* s)
2523 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2525 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2531 void force_nickchange(userrec* user,const char* newnick)
2538 FOREACH_RESULT(OnUserPreNick(user,newnick));
2540 kill_link(user,"Nickname collision");
2543 if (matches_qline(newnick))
2545 kill_link(user,"Nickname collision");
2553 strncpy(nick,newnick,MAXBUF);
2555 if (user->registered == 7)
2559 handle_nick(pars,1,user);
2565 int process_parameters(char **command_p,char *parameters)
2570 q = strlen(parameters);
2573 /* no parameters, command_p invalid! */
2576 if (parameters[0] == ':')
2578 command_p[0] = parameters+1;
2583 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2585 /* only one parameter */
2586 command_p[0] = parameters;
2587 if (parameters[0] == ':')
2589 if (strchr(parameters,' ') != NULL)
2597 command_p[j++] = parameters;
2598 for (int i = 0; i <= q; i++)
2600 if (parameters[i] == ' ')
2602 command_p[j++] = parameters+i+1;
2603 parameters[i] = '\0';
2604 if (command_p[j-1][0] == ':')
2606 *command_p[j-1]++; /* remove dodgy ":" */
2608 /* parameter like this marks end of the sequence */
2612 return j; /* returns total number of items in the list */
2615 void process_command(userrec *user, char* cmd)
2619 char *command_p[127];
2620 char p[MAXBUF], temp[MAXBUF];
2621 int i, j, items, cmd_found;
2623 for (int i = 0; i < 127; i++)
2624 command_p[i] = NULL;
2634 if (!strcmp(cmd,""))
2639 int total_params = 0;
2642 for (int q = 0; q < strlen(cmd)-1; q++)
2644 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2647 // found a 'trailing', we dont count them after this.
2655 // another phidjit bug...
2656 if (total_params > 126)
2658 //kill_link(user,"Protocol violation (1)");
2659 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2663 strlcpy(temp,cmd,MAXBUF);
2665 std::string tmp = cmd;
2666 for (int i = 0; i <= MODCOUNT; i++)
2668 std::string oldtmp = tmp;
2669 modules[i]->OnServerRaw(tmp,true,user);
2672 log(DEBUG,"A Module changed the input string!");
2673 log(DEBUG,"New string: %s",tmp.c_str());
2674 log(DEBUG,"Old string: %s",oldtmp.c_str());
2678 strlcpy(cmd,tmp.c_str(),MAXBUF);
2679 strlcpy(temp,cmd,MAXBUF);
2681 if (!strchr(cmd,' '))
2683 /* no parameters, lets skip the formalities and not chop up
2685 log(DEBUG,"About to preprocess command with no params");
2687 command_p[0] = NULL;
2689 for (int i = 0; i <= strlen(cmd); i++)
2691 cmd[i] = toupper(cmd[i]);
2693 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2700 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2701 for (int i = 0; i < strlen(temp); i++)
2703 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2709 /* split the full string into a command plus parameters */
2713 if (strchr(cmd,' '))
2715 for (int i = 0; i <= strlen(cmd); i++)
2717 /* capitalise the command ONLY, leave params intact */
2718 cmd[i] = toupper(cmd[i]);
2719 /* are we nearly there yet?! :P */
2723 parameters = cmd+i+1;
2731 for (int i = 0; i <= strlen(cmd); i++)
2733 cmd[i] = toupper(cmd[i]);
2740 if (strlen(command)>MAXCOMMAND)
2742 //kill_link(user,"Protocol violation (2)");
2743 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2747 for (int x = 0; x < strlen(command); x++)
2749 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2751 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2753 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2755 //kill_link(user,"Protocol violation (3)");
2756 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2763 for (int i = 0; i != cmdlist.size(); i++)
2765 if (strcmp(cmdlist[i].command,""))
2767 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2769 log(DEBUG,"Found matching command");
2773 if (strcmp(parameters,""))
2775 items = process_parameters(command_p,parameters);
2780 command_p[0] = NULL;
2786 command_p[0] = NULL;
2791 log(DEBUG,"Processing command");
2793 /* activity resets the ping pending timer */
2794 user->nping = time(NULL) + 120;
2795 if ((items) < cmdlist[i].min_params)
2797 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2798 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2801 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2803 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2804 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2808 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2810 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2811 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2815 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2817 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2819 if ((!isnick(user->nick)) || (user->registered != 7))
2821 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2822 WriteServ(user->fd,"451 %s :You have not registered",command);
2826 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2828 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2829 if (cmdlist[i].handler_function)
2831 /* ikky /stats counters */
2836 user->bytes_in += strlen(temp);
2839 cmdlist[i].use_count++;
2840 cmdlist[i].total_bytes+=strlen(temp);
2843 /* WARNING: nothing may come after the
2844 * command handler call, as the handler
2845 * may free the user structure! */
2847 cmdlist[i].handler_function(command_p,items,user);
2853 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2854 WriteServ(user->fd,"451 %s :You have not registered",command);
2862 if ((!cmd_found) && (user))
2864 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2865 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2870 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2873 /* create the command and push it onto the table */
2874 strlcpy(comm.command,cmd,MAXBUF);
2875 comm.handler_function = f;
2876 comm.flags_needed = flags;
2877 comm.min_params = minparams;
2879 comm.total_bytes = 0;
2880 cmdlist.push_back(comm);
2881 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2884 void SetupCommandTable(void)
2886 createcommand("USER",handle_user,0,4);
2887 createcommand("NICK",handle_nick,0,1);
2888 createcommand("QUIT",handle_quit,0,0);
2889 createcommand("VERSION",handle_version,0,0);
2890 createcommand("PING",handle_ping,0,1);
2891 createcommand("PONG",handle_pong,0,1);
2892 createcommand("ADMIN",handle_admin,0,0);
2893 createcommand("PRIVMSG",handle_privmsg,0,2);
2894 createcommand("INFO",handle_info,0,0);
2895 createcommand("TIME",handle_time,0,0);
2896 createcommand("WHOIS",handle_whois,0,1);
2897 createcommand("WALLOPS",handle_wallops,'o',1);
2898 createcommand("NOTICE",handle_notice,0,2);
2899 createcommand("JOIN",handle_join,0,1);
2900 createcommand("NAMES",handle_names,0,1);
2901 createcommand("PART",handle_part,0,1);
2902 createcommand("KICK",handle_kick,0,2);
2903 createcommand("MODE",handle_mode,0,1);
2904 createcommand("TOPIC",handle_topic,0,1);
2905 createcommand("WHO",handle_who,0,1);
2906 createcommand("MOTD",handle_motd,0,0);
2907 createcommand("RULES",handle_rules,0,0);
2908 createcommand("OPER",handle_oper,0,2);
2909 createcommand("LIST",handle_list,0,0);
2910 createcommand("DIE",handle_die,'o',1);
2911 createcommand("RESTART",handle_restart,'o',1);
2912 createcommand("KILL",handle_kill,'o',2);
2913 createcommand("REHASH",handle_rehash,'o',0);
2914 createcommand("LUSERS",handle_lusers,0,0);
2915 createcommand("STATS",handle_stats,0,1);
2916 createcommand("USERHOST",handle_userhost,0,1);
2917 createcommand("AWAY",handle_away,0,0);
2918 createcommand("ISON",handle_ison,0,0);
2919 createcommand("SUMMON",handle_summon,0,0);
2920 createcommand("USERS",handle_users,0,0);
2921 createcommand("INVITE",handle_invite,0,2);
2922 createcommand("PASS",handle_pass,0,1);
2923 createcommand("TRACE",handle_trace,'o',0);
2924 createcommand("WHOWAS",handle_whowas,0,1);
2925 createcommand("CONNECT",handle_connect,'o',1);
2926 createcommand("SQUIT",handle_squit,'o',0);
2927 createcommand("MODULES",handle_modules,'o',0);
2928 createcommand("LINKS",handle_links,0,0);
2929 createcommand("MAP",handle_map,0,0);
2930 createcommand("KLINE",handle_kline,'o',1);
2931 createcommand("GLINE",handle_gline,'o',1);
2932 createcommand("ZLINE",handle_zline,'o',1);
2933 createcommand("QLINE",handle_qline,'o',1);
2934 createcommand("SERVER",handle_server,0,0);
2937 void process_buffer(const char* cmdbuf,userrec *user)
2941 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2948 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2951 if (!strcmp(cmdbuf,""))
2955 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2957 strlcpy(cmd,cmdbuf,MAXBUF);
2958 if (!strcmp(cmd,""))
2962 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2964 cmd[strlen(cmd)-1] = '\0';
2966 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2968 cmd[strlen(cmd)-1] = '\0';
2971 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2973 cmd[strlen(cmd)-1] = '\0';
2976 if (!strcmp(cmd,""))
2980 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2982 if ((user) && (cmd))
2984 process_command(user,cmd);
2988 void DoSync(serverrec* serv, char* tcp_host)
2991 log(DEBUG,"Sending sync");
2992 // send start of sync marker: Y <timestamp>
2993 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2994 // except the ones its receiving it from.
2995 snprintf(data,MAXBUF,"Y %d",time(NULL));
2996 serv->SendPacket(data,tcp_host);
2997 // send users and channels
2998 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3000 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
3001 serv->SendPacket(data,tcp_host);
3002 if (strchr(u->second->modes,'o'))
3004 snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3005 serv->SendPacket(data,tcp_host);
3007 for (int i = 0; i <= MODCOUNT; i++)
3009 string_list l = modules[i]->OnUserSync(u->second);
3010 for (int j = 0; j < l.size(); j++)
3012 strlcpy(data,l[j].c_str(),MAXBUF);
3013 serv->SendPacket(data,tcp_host);
3016 if (strcmp(chlist(u->second),""))
3018 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3019 serv->SendPacket(data,tcp_host);
3022 // send channel modes, topics etc...
3023 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3025 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3026 serv->SendPacket(data,tcp_host);
3027 for (int i = 0; i <= MODCOUNT; i++)
3029 string_list l = modules[i]->OnChannelSync(c->second);
3030 for (int j = 0; j < l.size(); j++)
3032 strlcpy(data,l[j].c_str(),MAXBUF);
3033 serv->SendPacket(data,tcp_host);
3036 if (strcmp(c->second->topic,""))
3038 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3039 serv->SendPacket(data,tcp_host);
3041 // send current banlist
3043 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3045 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3046 serv->SendPacket(data,tcp_host);
3049 // sync global zlines, glines, etc
3050 sync_xlines(serv,tcp_host);
3052 for (int j = 0; j < 32; j++)
3056 for (int k = 0; k < me[j]->connectors.size(); k++)
3058 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3060 snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3061 serv->SendPacket(data,tcp_host);
3062 NetSendMyRoutingTable();
3068 snprintf(data,MAXBUF,"F %d",time(NULL));
3069 serv->SendPacket(data,tcp_host);
3070 log(DEBUG,"Sent sync");
3071 // ircd sends its serverlist after the end of sync here
3075 void NetSendMyRoutingTable()
3077 // send out a line saying what is reachable to us.
3078 // E.g. if A is linked to B C and D, send out:
3080 // if its only linked to B and D send out:
3082 // if it has no links, dont even send out the line at all.
3083 char buffer[MAXBUF];
3084 snprintf(buffer,MAXBUF,"$ %s",ServerName);
3085 bool sendit = false;
3086 for (int i = 0; i < 32; i++)
3090 for (int j = 0; j < me[i]->connectors.size(); j++)
3092 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3094 strlcat(buffer," ",MAXBUF);
3095 strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3102 NetSendToAll(buffer);
3106 void DoSplit(const char* params)
3108 bool go_again = true;
3112 for (int i = 0; i < 32; i++)
3116 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3118 if (!strcasecmp(j->GetServerName().c_str(),params))
3121 j->CloseConnection();
3122 me[i]->connectors.erase(j);
3130 log(DEBUG,"Removed server. Will remove clients...");
3131 // iterate through the userlist and remove all users on this server.
3132 // because we're dealing with a mesh, we dont have to deal with anything
3133 // "down-route" from this server (nice huh)
3135 char reason[MAXBUF];
3136 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3140 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3142 if (!strcasecmp(u->second->server,params))
3144 kill_link(u->second,reason);
3152 // removes a server. Will NOT remove its users!
3154 void RemoveServer(const char* name)
3156 bool go_again = true;
3160 for (int i = 0; i < 32; i++)
3164 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3166 if (!strcasecmp(j->GetServerName().c_str(),name))
3169 j->CloseConnection();
3170 me[i]->connectors.erase(j);
3181 int reap_counter = 0;
3185 struct sockaddr_in client,server;
3186 char addrs[MAXBUF][255];
3187 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3190 int selectResult = 0, selectResult2 = 0;
3191 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3192 char resolvedHost[MAXBUF];
3196 log_file = fopen("ircd.log","a+");
3199 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3203 log(DEBUG,"InspIRCd: startup: begin");
3207 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3209 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3211 SetupCommandTable();
3212 log(DEBUG,"InspIRCd: startup: default command table set up");
3214 ReadConfig(true,NULL);
3215 if (strcmp(DieValue,""))
3217 printf("WARNING: %s\n\n",DieValue);
3220 log(DEBUG,"InspIRCd: startup: read config");
3222 int count2 = 0, count3 = 0;
3224 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3226 ConfValue("bind","port",count,configToken,&config_f);
3227 ConfValue("bind","address",count,Addr,&config_f);
3228 ConfValue("bind","type",count,Type,&config_f);
3229 if (!strcmp(Type,"servers"))
3231 char Default[MAXBUF];
3232 strcpy(Default,"no");
3233 ConfValue("bind","default",count,Default,&config_f);
3234 if (strchr(Default,'y'))
3236 defaultRoute = count3;
3237 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3239 me[count3] = new serverrec(ServerName,100L,false);
3240 if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3242 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3251 ports[count2] = atoi(configToken);
3252 strlcpy(addrs[count2],Addr,256);
3255 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3258 UDPportCount = count3;
3260 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3262 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3266 /* BugFix By Craig! :p */
3268 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3270 char modfile[MAXBUF];
3271 ConfValue("module","name",count2,configToken,&config_f);
3272 snprintf(modfile,MAXBUF,"%s/%s",MOD_PATH,configToken,&config_f);
3273 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3274 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3275 /* If The File Doesnt exist, Trying to load it
3276 * Will Segfault the IRCd.. So, check to see if
3277 * it Exists, Before Proceeding. */
3278 if (FileExists(modfile))
3280 factory[count] = new ircd_module(modfile);
3281 if (factory[count]->LastError())
3283 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3284 printf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3287 if (factory[count]->factory)
3289 modules[count] = factory[count]->factory->CreateModule();
3290 /* save the module and the module's classfactory, if
3291 * this isnt done, random crashes can occur :/ */
3292 module_names.push_back(modfile);
3296 log(DEBUG,"Unable to load %s",modfile);
3297 printf("Unable to load %s\nExiting...\n",modfile);
3300 /* Increase the Count */
3305 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3306 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3309 MODCOUNT = count - 1;
3310 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3312 printf("\nInspIRCd is now running!\n");
3314 startup_time = time(NULL);
3318 log(VERBOSE,"Not forking as -nofork was specified");
3322 if (DaemonSeed() == ERROR)
3324 log(DEBUG,"InspIRCd: startup: can't daemonise");
3325 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3331 /* setup select call */
3332 FD_ZERO(&selectFds);
3333 log(DEBUG,"InspIRCd: startup: zero selects");
3334 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3336 for (count = 0; count < portCount; count++)
3338 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3340 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3343 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3345 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3347 else /* well we at least bound to one socket so we'll continue */
3353 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3355 /* if we didn't bind to anything then abort */
3356 if (boundPortCount == 0)
3358 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3363 length = sizeof (client);
3364 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3366 /* main loop, this never returns */
3369 #ifdef _POSIX_PRIORITY_SCHEDULING
3372 // update the status of klines, etc
3379 user_hash::iterator count2 = clientlist.begin();
3381 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3382 // them in a list, then reap the list every second or so.
3383 if (reap_counter>300)
3385 if (fd_reap.size() > 0)
3387 for( int n = 0; n < fd_reap.size(); n++)
3389 Blocking(fd_reap[n]);
3391 NonBlocking(fd_reap[n]);
3400 FD_ZERO(&serverfds);
3403 for (int x = 0; x != UDPportCount; x++)
3406 FD_SET(me[x]->fd, &serverfds);
3412 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3415 for (int x = 0; x != UDPportCount; x++)
3417 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3419 char remotehost[MAXBUF],resolved[MAXBUF];
3420 length = sizeof (client);
3421 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3422 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3423 if(CleanAndResolve(resolved, remotehost) != TRUE)
3425 strlcpy(resolved,remotehost,MAXBUF);
3427 // add to this connections ircd_connector vector
3428 // *FIX* - we need the LOCAL port not the remote port in &client!
3429 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3434 for (int x = 0; x < UDPportCount; x++)
3436 std::deque<std::string> msgs;
3438 if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3440 for (int ctr = 0; ctr < msgs.size(); ctr++)
3442 char udp_msg[MAXBUF];
3443 strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3444 if (strlen(udp_msg)<1)
3446 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3449 // during a netburst, send all data to all other linked servers
3450 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3452 if (is_uline(tcp_host))
3454 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3456 NetSendToAllExcept(tcp_host,udp_msg);
3460 NetSendToAllExcept(tcp_host,udp_msg);
3462 FOREACH_MOD OnPacketReceive(udp_msg);
3463 handle_link_packet(udp_msg, tcp_host, me[x]);
3470 while (count2 != clientlist.end())
3473 tval.tv_usec = tval.tv_sec = 0;
3475 int total_in_this_set = 0;
3477 user_hash::iterator xcount = count2;
3478 user_hash::iterator endingiter = count2;
3480 if (!count2->second) break;
3483 if (count2->second->fd != 0)
3485 // assemble up to 64 sockets into an fd_set
3486 // to implement a pooling mechanism.
3488 // This should be up to 64x faster than the
3489 // old implementation.
3490 while (total_in_this_set < 64)
3492 if (count2 != clientlist.end())
3494 // we don't check the state of remote users.
3495 if (count2->second->fd > 0)
3497 FD_SET (count2->second->fd, &sfd);
3499 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3500 // their connection class.
3501 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3503 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3504 kill_link(count2->second,"Registration timeout");
3507 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3509 if ((!count2->second->lastping) && (count2->second->registered == 7))
3511 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3512 kill_link(count2->second,"Ping timeout");
3515 Write(count2->second->fd,"PING :%s",ServerName);
3516 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3517 count2->second->lastping = 0;
3518 count2->second->nping = time(NULL)+120;
3522 total_in_this_set++;
3527 endingiter = count2;
3528 count2 = xcount; // roll back to where we were
3534 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3536 // now loop through all of the items in this pool if any are waiting
3537 //if (selectResult2 > 0)
3538 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3541 #ifdef _POSIX_PRIORITY_SCHEDULING
3546 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3548 log(DEBUG,"Reading fd %d",count2a->second->fd);
3549 memset(data, 0, 10240);
3550 result = read(count2a->second->fd, data, 10240);
3555 log(DEBUG,"Read %d characters from socket",result);
3556 userrec* current = count2a->second;
3557 int currfd = current->fd;
3558 char* l = strtok(data,"\n");
3563 if ((floodlines > current->flood) && (current->flood != 0))
3565 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3566 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3567 kill_link(current,"Excess flood");
3570 char sanitized[NetBufferSize];
3571 memset(sanitized, 0, NetBufferSize);
3573 for (int pt = 0; pt < strlen(l); pt++)
3577 sanitized[ptt++] = l[pt];
3580 sanitized[ptt] = '\0';
3581 if (strlen(sanitized))
3585 // we're gonna re-scan to check if the nick is gone, after every
3586 // command - if it has, we're gonna bail
3587 bool find_again = false;
3588 process_buffer(sanitized,current);
3590 // look for the user's record in case it's changed
3591 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3593 if (c2->second->fd == currfd)
3595 // found again, update pointer
3596 current == c2->second;
3605 l = strtok(NULL,"\n");
3610 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3612 log(DEBUG,"killing: %s",count2a->second->nick);
3613 kill_link(count2a->second,strerror(errno));
3617 // result EAGAIN means nothing read
3618 if (result == EAGAIN)
3626 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3627 kill_link(count2a->second,"Client exited");
3628 // must bail here? kill_link removes the hash, corrupting the iterator
3629 log(DEBUG,"Bailing from client exit");
3633 else if (result > 0)
3638 for (int q = 0; q < total_in_this_set; q++)
3640 // there is no iterator += operator :(
3641 //if (count2 != clientlist.end())
3648 // set up select call
3649 for (count = 0; count < boundPortCount; count++)
3651 FD_SET (openSockfd[count], &selectFds);
3655 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3657 /* select is reporting a waiting socket. Poll them all to find out which */
3658 if (selectResult > 0)
3660 char target[MAXBUF], resolved[MAXBUF];
3661 for (count = 0; count < boundPortCount; count++)
3663 if (FD_ISSET (openSockfd[count], &selectFds))
3665 length = sizeof (client);
3666 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3668 address_cache::iterator iter = IP.find(client.sin_addr);
3669 bool iscached = false;
3670 if (iter == IP.end())
3672 /* ip isn't in cache, add it */
3673 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3674 if(CleanAndResolve(resolved, target) != TRUE)
3676 strlcpy(resolved,target,MAXBUF);
3678 /* hostname now in 'target' */
3679 IP[client.sin_addr] = new string(resolved);
3680 /* hostname in cache */
3684 /* found ip (cached) */
3685 strlcpy(resolved, iter->second->c_str(), MAXBUF);
3689 if (incomingSockfd < 0)
3691 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3692 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3696 AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3697 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3704 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3707 close (incomingSockfd);