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 vector<Module*> modules;
93 std::vector<std::string> module_names;
94 extern vector<ircd_module*> factory;
95 std::vector<int> fd_reap;
103 template<> struct nspace::hash<in_addr>
105 size_t operator()(const struct in_addr &a) const
108 memcpy(&q,&a,sizeof(size_t));
113 template<> struct nspace::hash<string>
115 size_t operator()(const string &s) const
118 static struct hash<const char *> strhash;
130 bool operator()(const string& s1, const string& s2) const
132 char a[MAXBUF],b[MAXBUF];
133 strcpy(a,s1.c_str());
134 strcpy(b,s2.c_str());
135 return (strcasecmp(a,b) == 0);
140 struct InAddr_HashComp
143 bool operator()(const in_addr &s1, const in_addr &s2) const
148 memcpy(&q,&s1,sizeof(size_t));
149 memcpy(&p,&s2,sizeof(size_t));
157 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
158 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
159 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
160 typedef std::deque<command_t> command_table;
166 user_hash clientlist;
169 command_table cmdlist;
176 struct linger linger = { 0 };
177 char bannerBuffer[MAXBUF];
178 int boundPortCount = 0;
179 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
180 int defaultRoute = 0;
184 long MyKey = C.GenKey();
188 int has_channel(userrec *u, chanrec *c);
189 int usercount(chanrec *c);
190 int usercount_i(chanrec *c);
191 void update_stats_l(int fd,int data_out);
192 char* Passwd(userrec *user);
193 bool IsDenied(userrec *user);
194 void AddWhoWas(userrec* u);
196 std::vector<long> auth_cookies;
197 std::stringstream config_f(stringstream::in | stringstream::out);
203 char Revision[] = "$Revision$";
206 char *v1 = strtok_r(s1," ",&savept);
208 char *v2 = strtok_r(s1," ",&savept);
210 return (long)(atof(v2)*10000);
214 std::string getservername()
219 std::string getserverdesc()
224 std::string getnetworkname()
229 std::string getadminname()
234 std::string getadminemail()
239 std::string getadminnick()
244 void log(int level,char *text, ...)
246 char textbuffer[MAXBUF];
249 struct tm * timeinfo;
250 if (level < LogLevel)
254 timeinfo = localtime (&rawtime);
259 va_start (argsPtr, text);
260 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
262 strcpy(b,asctime(timeinfo));
263 b[strlen(b)-1] = ':';
264 fprintf(log_file,"%s %s\n",b,textbuffer);
267 // nofork enabled? display it on terminal too
268 printf("%s %s\n",b,textbuffer);
273 void readfile(file_cache &F, const char* fname)
276 char linebuf[MAXBUF];
278 log(DEBUG,"readfile: loading %s",fname);
280 file = fopen(fname,"r");
285 fgets(linebuf,sizeof(linebuf),file);
286 linebuf[strlen(linebuf)-1]='\0';
287 if (!strcmp(linebuf,""))
293 F.push_back(linebuf);
300 log(DEBUG,"readfile: failed to load file: %s",fname);
302 log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
305 void ReadConfig(void)
307 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
308 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF];
311 LoadConf(CONFIG_FILE,&config_f);
313 ConfValue("server","name",0,ServerName,&config_f);
314 ConfValue("server","description",0,ServerDesc,&config_f);
315 ConfValue("server","network",0,Network,&config_f);
316 ConfValue("admin","name",0,AdminName,&config_f);
317 ConfValue("admin","email",0,AdminEmail,&config_f);
318 ConfValue("admin","nick",0,AdminNick,&config_f);
319 ConfValue("files","motd",0,motd,&config_f);
320 ConfValue("files","rules",0,rules,&config_f);
321 ConfValue("power","diepass",0,diepass,&config_f);
322 ConfValue("power","pause",0,pauseval,&config_f);
323 ConfValue("power","restartpass",0,restartpass,&config_f);
324 ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
325 ConfValue("die","value",0,DieValue,&config_f);
326 ConfValue("options","loglevel",0,dbg,&config_f);
327 ConfValue("options","netbuffersize",0,NB,&config_f);
328 ConfValue("options","maxwho",0,MW,&config_f);
329 ConfValue("options","allowhalfop",0,AH,&config_f);
330 ConfValue("options","allowprotect",0,AP,&config_f);
331 ConfValue("options","allowfounder",0,AF,&config_f);
332 NetBufferSize = atoi(NB);
333 MaxWhoResults = atoi(MW);
334 AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
335 AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
336 AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
337 if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
339 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
340 NetBufferSize = 10240;
342 if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
344 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
347 if (!strcmp(dbg,"debug"))
349 if (!strcmp(dbg,"verbose"))
351 if (!strcmp(dbg,"default"))
353 if (!strcmp(dbg,"sparse"))
355 if (!strcmp(dbg,"none"))
358 log(DEFAULT,"Reading message of the day...");
359 readfile(RULES,rules);
360 log(DEFAULT,"Reading connect classes...");
362 for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
365 ConfValue("connect","allow",i,Value,&config_f);
366 ConfValue("connect","timeout",i,timeout,&config_f);
367 ConfValue("connect","flood",i,flood,&config_f);
368 if (strcmp(Value,""))
370 strcpy(c.host,Value);
373 ConfValue("connect","password",i,Value,&config_f);
374 strcpy(c.pass,Value);
375 c.registration_timeout = 90; // default is 2 minutes
376 c.flood = atoi(flood);
379 c.registration_timeout = atoi(timeout);
381 Classes.push_back(c);
382 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
386 ConfValue("connect","deny",i,Value,&config_f);
387 strcpy(c.host,Value);
389 Classes.push_back(c);
390 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
394 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
395 read_xline_defaults();
396 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
398 log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
401 /* write formatted text to a socket, in same format as printf */
403 void Write(int sock,char *text, ...)
407 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
410 char textbuffer[MAXBUF];
414 va_start (argsPtr, text);
415 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
417 sprintf(tb,"%s\r\n",textbuffer);
421 write(sock,tb,strlen(tb));
422 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
426 /* write a server formatted numeric response to a single socket */
428 void WriteServ(int sock, char* text, ...)
432 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
435 char textbuffer[MAXBUF],tb[MAXBUF];
437 va_start (argsPtr, text);
439 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
441 sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
445 write(sock,tb,strlen(tb));
446 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
450 /* write text from an originating user to originating user */
452 void WriteFrom(int sock, userrec *user,char* text, ...)
454 if ((!text) || (!user))
456 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
459 char textbuffer[MAXBUF],tb[MAXBUF];
461 va_start (argsPtr, text);
463 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
465 sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
469 write(sock,tb,strlen(tb));
470 update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
474 /* write text to an destination user from a source user (e.g. user privmsg) */
476 void WriteTo(userrec *source, userrec *dest,char *data, ...)
478 if ((!dest) || (!data))
480 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
483 char textbuffer[MAXBUF],tb[MAXBUF];
485 va_start (argsPtr, data);
486 vsnprintf(textbuffer, MAXBUF, data, argsPtr);
490 // if no source given send it from the server.
493 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
497 WriteFrom(dest->fd,source,"%s",textbuffer);
501 /* write formatted text from a source user to all users on a channel
502 * including the sender (NOT for privmsg, notice etc!) */
504 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
506 if ((!Ptr) || (!user) || (!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 WriteTo(user,i->second,"%s",textbuffer);
525 /* write formatted text from a source user to all users on a channel
526 * including the sender (NOT for privmsg, notice etc!) doesnt send to
527 * users on remote servers */
529 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
531 if ((!Ptr) || (!text))
533 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
536 char textbuffer[MAXBUF];
538 va_start (argsPtr, text);
539 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
541 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
543 if (has_channel(i->second,Ptr))
545 if (i->second->fd != -1)
549 WriteServ(i->second->fd,"%s",textbuffer);
553 WriteTo(user,i->second,"%s",textbuffer);
561 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
563 if ((!Ptr) || (!user) || (!text))
565 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
568 char textbuffer[MAXBUF];
570 va_start (argsPtr, text);
571 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
573 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
577 if (has_channel(i->second,Ptr))
579 WriteServ(i->second->fd,"%s",textbuffer);
586 /* write formatted text from a source user to all users on a channel except
587 * for the sender (for privmsg etc) */
589 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
591 if ((!Ptr) || (!user) || (!text))
593 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
596 char textbuffer[MAXBUF];
598 va_start (argsPtr, text);
599 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
602 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
606 if (has_channel(i->second,Ptr) && (user != i->second))
608 WriteTo(user,i->second,"%s",textbuffer);
615 std::string GetServerDescription(char* servername)
617 for (int j = 0; j < 32; j++)
621 for (int k = 0; k < me[j]->connectors.size(); k++)
623 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
625 return me[j]->connectors[k].GetDescription();
629 return ServerDesc; // not a remote server that can be found, it must be me.
634 /* write a formatted string to all users who share at least one common
635 * channel, including the source user e.g. for use in NICK */
637 void WriteCommon(userrec *u, char* text, ...)
641 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
645 if (u->registered != 7) {
646 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
650 char textbuffer[MAXBUF];
652 va_start (argsPtr, text);
653 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
656 WriteFrom(u->fd,u,"%s",textbuffer);
658 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
662 if (common_channels(u,i->second) && (i->second != u))
664 WriteFrom(i->second->fd,u,"%s",textbuffer);
670 /* write a formatted string to all users who share at least one common
671 * channel, NOT including the source user e.g. for use in QUIT */
673 void WriteCommonExcept(userrec *u, char* text, ...)
677 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
681 if (u->registered != 7) {
682 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
686 char textbuffer[MAXBUF];
688 va_start (argsPtr, text);
689 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
692 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
696 if ((common_channels(u,i->second)) && (u != i->second))
698 WriteFrom(i->second->fd,u,"%s",textbuffer);
704 void WriteOpers(char* text, ...)
708 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
712 char textbuffer[MAXBUF];
714 va_start (argsPtr, text);
715 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
718 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
722 if (strchr(i->second->modes,'o'))
724 if (strchr(i->second->modes,'s'))
726 // send server notices to all with +s
727 // (TODO: needs SNOMASKs)
728 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
735 // returns TRUE of any users on channel C occupy server 'servername'.
737 bool ChanAnyOnThisServer(chanrec *c,char* servername)
739 log(DEBUG,"ChanAnyOnThisServer");
740 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
742 if (has_channel(i->second,c))
744 if (!strcasecmp(i->second->server,servername))
753 // returns true if user 'u' shares any common channels with any users on server 'servername'
755 bool CommonOnThisServer(userrec* u,const char* servername)
757 log(DEBUG,"ChanAnyOnThisServer");
758 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
760 if ((common_channels(u,i->second)) && (u != i->second))
762 if (!strcasecmp(i->second->server,servername))
764 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
773 void NetSendToCommon(userrec* u, char* s)
776 snprintf(buffer,MAXBUF,"%s",s);
778 log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
780 for (int j = 0; j < 32; j++)
784 for (int k = 0; k < me[j]->connectors.size(); k++)
786 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
788 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
796 void NetSendToAll(char* s)
799 snprintf(buffer,MAXBUF,"%s",s);
801 log(DEBUG,"NetSendToAll: '%s'",s);
803 for (int j = 0; j < 32; j++)
807 for (int k = 0; k < me[j]->connectors.size(); k++)
809 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
815 void NetSendToAllAlive(char* s)
818 snprintf(buffer,MAXBUF,"%s",s);
820 log(DEBUG,"NetSendToAllAlive: '%s'",s);
822 for (int j = 0; j < 32; j++)
826 for (int k = 0; k < me[j]->connectors.size(); k++)
828 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
830 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
834 log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
842 void NetSendToOne(char* target,char* s)
845 snprintf(buffer,MAXBUF,"%s",s);
847 log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
849 for (int j = 0; j < 32; j++)
853 for (int k = 0; k < me[j]->connectors.size(); k++)
855 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
857 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
864 void NetSendToAllExcept(const char* target,char* s)
867 snprintf(buffer,MAXBUF,"%s",s);
869 log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
871 for (int j = 0; j < 32; j++)
875 for (int k = 0; k < me[j]->connectors.size(); k++)
877 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
879 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
887 void WriteMode(const char* modes, int flags, const char* text, ...)
889 if ((!text) || (!modes) || (!flags))
891 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
895 char textbuffer[MAXBUF];
897 va_start (argsPtr, text);
898 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
901 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
905 bool send_to_user = false;
910 for (int n = 0; n < strlen(modes); n++)
912 if (!hasumode(i->second,modes[n]))
914 send_to_user = false;
919 else if (flags == WM_OR)
921 send_to_user = false;
922 for (int n = 0; n < strlen(modes); n++)
924 if (hasumode(i->second,modes[n]))
934 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
941 void WriteWallOps(userrec *source, bool local_only, char* text, ...)
943 if ((!text) || (!source))
945 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
950 char textbuffer[MAXBUF];
952 va_start (argsPtr, text);
953 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
956 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
960 if (strchr(i->second->modes,'w'))
962 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
970 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
971 NetSendToAll(buffer);
975 /* convert a string to lowercase. Note following special circumstances
976 * taken from RFC 1459. Many "official" server branches still hold to this
977 * rule so i will too;
979 * Because of IRC's scandanavian origin, the characters {}| are
980 * considered to be the lower case equivalents of the characters []\,
981 * respectively. This is a critical issue when determining the
982 * equivalence of two nicknames.
985 void strlower(char *n)
991 for (int i = 0; i != strlen(n); i++)
993 n[i] = tolower(n[i]);
1005 /* Find a user record by nickname and return a pointer to it */
1007 userrec* Find(string nick)
1009 user_hash::iterator iter = clientlist.find(nick);
1011 if (iter == clientlist.end())
1012 /* Couldn't find it */
1015 return iter->second;
1018 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1020 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1024 if (i->second->fd == fd)
1026 i->second->bytes_out+=data_out;
1027 i->second->cmds_out++;
1034 /* find a channel record by channel name and return a pointer to it */
1036 chanrec* FindChan(const char* chan)
1040 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1044 chan_hash::iterator iter = chanlist.find(chan);
1046 if (iter == chanlist.end())
1047 /* Couldn't find it */
1050 return iter->second;
1054 void purge_empty_chans(void)
1056 int go_again = 1, purge = 0;
1061 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1064 if (!usercount(i->second))
1066 /* kill the record */
1067 if (i != chanlist.end())
1069 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1079 log(DEBUG,"skipped purge for %s",i->second->name);
1084 log(DEBUG,"completed channel purge, killed %d",purge);
1088 char scratch[MAXBUF];
1089 char sparam[MAXBUF];
1091 char* chanmodes(chanrec *chan)
1095 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1102 if (chan->noexternal)
1104 strncat(scratch,"n",MAXMODES);
1106 if (chan->topiclock)
1108 strncat(scratch,"t",MAXMODES);
1110 if (strcmp(chan->key,""))
1112 strncat(scratch,"k",MAXMODES);
1116 strncat(scratch,"l",MAXMODES);
1118 if (chan->inviteonly)
1120 strncat(scratch,"i",MAXMODES);
1122 if (chan->moderated)
1124 strncat(scratch,"m",MAXMODES);
1128 strncat(scratch,"s",MAXMODES);
1130 if (chan->c_private)
1132 strncat(scratch,"p",MAXMODES);
1134 if (strcmp(chan->key,""))
1136 strncat(sparam," ",MAXBUF);
1137 strncat(sparam,chan->key,MAXBUF);
1142 sprintf(foo," %d",chan->limit);
1143 strncat(sparam,foo,MAXBUF);
1145 if (strlen(chan->custom_modes))
1147 strncat(scratch,chan->custom_modes,MAXMODES);
1148 for (int z = 0; z < strlen(chan->custom_modes); z++)
1150 std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1153 strncat(sparam," ",MAXBUF);
1154 strncat(sparam,extparam.c_str(),MAXBUF);
1158 log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1159 strncat(scratch,sparam,MAXMODES);
1164 /* compile a userlist of a channel into a string, each nick seperated by
1165 * spaces and op, voice etc status shown as @ and + */
1167 void userlist(userrec *user,chanrec *c)
1169 if ((!c) || (!user))
1171 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1175 sprintf(list,"353 %s = %s :", user->nick, c->name);
1176 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1178 if (has_channel(i->second,c))
1180 if (isnick(i->second->nick))
1182 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1184 /* user is +i, and source not on the channel, does not show
1185 * nick in NAMES list */
1188 strcat(list,cmode(i->second,c));
1189 strcat(list,i->second->nick);
1191 if (strlen(list)>(480-NICKMAX))
1193 /* list overflowed into
1194 * multiple numerics */
1195 WriteServ(user->fd,list);
1196 sprintf(list,"353 %s = %s :", user->nick, c->name);
1201 /* if whats left in the list isnt empty, send it */
1202 if (list[strlen(list)-1] != ':')
1204 WriteServ(user->fd,list);
1208 /* return a count of the users on a specific channel accounting for
1209 * invisible users who won't increase the count. e.g. for /LIST */
1211 int usercount_i(chanrec *c)
1218 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1223 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1227 if (has_channel(i->second,c))
1229 if (isnick(i->second->nick))
1231 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1233 /* user is +i, and source not on the channel, does not show
1234 * nick in NAMES list */
1242 log(DEBUG,"usercount_i: %s %d",c->name,count);
1247 int usercount(chanrec *c)
1254 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1259 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1263 if (has_channel(i->second,c))
1265 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1272 log(DEBUG,"usercount: %s %d",c->name,count);
1277 /* add a channel to a user, creating the record for it if needed and linking
1278 * it to the user record */
1280 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1282 if ((!user) || (!cn))
1284 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1293 strncpy(cname,cn,MAXBUF);
1295 // we MUST declare this wherever we use FOREACH_RESULT
1298 if (strlen(cname) > CHANMAX-1)
1300 cname[CHANMAX-1] = '\0';
1303 log(DEBUG,"add_channel: %s %s",user->nick,cname);
1305 if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1307 return NULL; // already on the channel!
1311 if (!FindChan(cname))
1314 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1319 /* create a new one */
1320 log(DEBUG,"add_channel: creating: %s",cname);
1322 chanlist[cname] = new chanrec();
1324 strcpy(chanlist[cname]->name, cname);
1325 chanlist[cname]->topiclock = 1;
1326 chanlist[cname]->noexternal = 1;
1327 chanlist[cname]->created = time(NULL);
1328 strcpy(chanlist[cname]->topic, "");
1329 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1330 chanlist[cname]->topicset = 0;
1331 Ptr = chanlist[cname];
1332 log(DEBUG,"add_channel: created: %s",cname);
1333 /* set created to 2 to indicate user
1334 * is the first in the channel
1335 * and should be given ops */
1341 /* channel exists, just fish out a pointer to its struct */
1342 Ptr = FindChan(cname);
1345 log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1347 // the override flag allows us to bypass channel modes
1348 // and bans (used by servers)
1352 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1357 if (strcmp(Ptr->key,""))
1359 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1362 log(DEBUG,"add_channel: no key given in JOIN");
1363 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1368 log(DEBUG,"key at %p is %s",key,key);
1369 if (strcasecmp(key,Ptr->key))
1371 log(DEBUG,"add_channel: bad key given in JOIN");
1372 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1377 log(DEBUG,"add_channel: no key");
1379 if (Ptr->inviteonly)
1381 log(DEBUG,"add_channel: channel is +i");
1382 if (user->IsInvited(Ptr->name))
1384 /* user was invited to channel */
1385 /* there may be an optional channel NOTICE here */
1389 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1393 log(DEBUG,"add_channel: channel is not +i");
1397 if (usercount(Ptr) == Ptr->limit)
1399 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1404 log(DEBUG,"add_channel: about to walk banlist");
1406 /* check user against the channel banlist */
1409 if (Ptr->bans.size())
1411 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1413 if (match(user->GetFullHost(),i->data))
1415 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1422 log(DEBUG,"add_channel: bans checked");
1425 if ((Ptr) && (user))
1427 user->RemoveInvite(Ptr->name);
1430 log(DEBUG,"add_channel: invites removed");
1435 log(DEBUG,"Overridden checks");
1443 log(DEBUG,"Passed channel checks");
1445 for (int i =0; i != MAXCHANS; i++)
1447 log(DEBUG,"Check location %d",i);
1448 if (user->chans[i].channel == NULL)
1450 log(DEBUG,"Adding into their channel list at location %d",i);
1454 /* first user in is given ops */
1455 user->chans[i].uc_modes = UCMODE_OP;
1459 user->chans[i].uc_modes = 0;
1461 user->chans[i].channel = Ptr;
1462 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1464 if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1466 // use the stamdard J token with no privilages.
1467 char buffer[MAXBUF];
1470 snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1474 snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1476 NetSendToAll(buffer);
1479 log(DEBUG,"Sent JOIN to client");
1483 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1484 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1487 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1488 WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1489 WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1490 FOREACH_MOD OnUserJoin(user,Ptr);
1494 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1495 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1499 /* remove a channel from a users record, and remove the record from memory
1500 * if the channel has become empty */
1502 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1504 if ((!user) || (!cname))
1506 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1513 if ((!cname) || (!user))
1518 Ptr = FindChan(cname);
1525 FOREACH_MOD OnUserPart(user,Ptr);
1526 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1528 for (int i =0; i != MAXCHANS; i++)
1530 /* zap it from the channel list of the user */
1531 if (user->chans[i].channel == Ptr)
1535 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1539 char buffer[MAXBUF];
1540 snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1541 NetSendToAll(buffer);
1550 char buffer[MAXBUF];
1551 snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1552 NetSendToAll(buffer);
1555 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1557 user->chans[i].uc_modes = 0;
1558 user->chans[i].channel = NULL;
1559 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1564 /* if there are no users left on the channel */
1565 if (!usercount(Ptr))
1567 chan_hash::iterator iter = chanlist.find(Ptr->name);
1569 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1571 /* kill the record */
1572 if (iter != chanlist.end())
1574 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1575 delete iter->second;
1576 chanlist.erase(iter);
1582 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1584 if ((!src) || (!user) || (!Ptr) || (!reason))
1586 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1593 if ((!Ptr) || (!user) || (!src))
1598 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1600 if (!has_channel(user,Ptr))
1602 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1607 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1609 if (MOD_RESULT == ACR_DENY)
1612 if (MOD_RESULT == ACR_DEFAULT)
1614 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1616 if (cstatus(src,Ptr) == STATUS_HOP)
1618 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1622 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1629 for (int i =0; i != MAXCHANS; i++)
1631 /* zap it from the channel list of the user */
1632 if (user->chans[i].channel)
1633 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1635 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1636 user->chans[i].uc_modes = 0;
1637 user->chans[i].channel = NULL;
1638 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1643 /* if there are no users left on the channel */
1644 if (!usercount(Ptr))
1646 chan_hash::iterator iter = chanlist.find(Ptr->name);
1648 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1650 /* kill the record */
1651 if (iter != chanlist.end())
1653 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1654 delete iter->second;
1655 chanlist.erase(iter);
1663 /* This function pokes and hacks at a parameter list like the following:
1665 * PART #winbot, #darkgalaxy :m00!
1667 * to turn it into a series of individual calls like this:
1669 * PART #winbot :m00!
1670 * PART #darkgalaxy :m00!
1672 * The seperate calls are sent to a callback function provided by the caller
1673 * (the caller will usually call itself recursively). The callback function
1674 * must be a command handler. Calling this function on a line with no list causes
1675 * no action to be taken. You must provide a starting and ending parameter number
1676 * where the range of the list can be found, useful if you have a terminating
1677 * parameter as above which is actually not part of the list, or parameters
1678 * before the actual list as well. This code is used by many functions which
1679 * can function as "one to list" (see the RFC) */
1681 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1686 char blog[32][MAXBUF];
1687 char blog2[32][MAXBUF];
1688 int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1689 char keystr[MAXBUF];
1692 for (int i = 0; i <32; i++)
1695 for (int i = 0; i <32; i++)
1696 strcpy(blog2[i],"");
1699 for (int i = 0; i <10; i++)
1703 parameters[i] = moo;
1708 if (pcnt > 1) /* we have a key to copy */
1710 strcpy(keystr,parameters[1]);
1714 if (!parameters[start])
1718 if (!strchr(parameters[start],','))
1723 for (int i = start; i <= end; i++)
1727 strcat(plist,parameters[i]);
1735 for (int i = 0; i < t; i++)
1737 if (plist[i] == ',')
1740 strcpy(blog[j++],param);
1744 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1749 strcpy(blog[j++],param);
1752 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1757 if ((joins) && (keystr))
1759 if (strchr(keystr,','))
1763 t2 = strlen(keystr);
1764 for (int i = 0; i < t2; i++)
1766 if (keystr[i] == ',')
1769 strcpy(blog2[j++],param);
1773 strcpy(blog2[j++],param);
1778 for (j = 0; j < total; j++)
1784 for (q = end; q < pcnt-1; q++)
1786 if (parameters[q+1])
1788 pars[q-end+1] = parameters[q+1];
1791 if ((joins) && (parameters[1]))
1802 /* repeatedly call the function with the hacked parameter list */
1803 if ((joins) && (pcnt > 1))
1807 // pars[1] already set up and containing key from blog2[j]
1812 pars[1] = parameters[1];
1818 fn(pars,pcnt-(end-start),u);
1827 void kill_link(userrec *user,const char* r)
1829 user_hash::iterator iter = clientlist.find(user->nick);
1831 char reason[MAXBUF];
1833 strncpy(reason,r,MAXBUF);
1835 if (strlen(reason)>MAXQUIT)
1837 reason[MAXQUIT-1] = '\0';
1840 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1841 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1842 log(DEBUG,"closing fd %d",user->fd);
1844 /* bugfix, cant close() a nonblocking socket (sux!) */
1845 if (user->registered == 7) {
1846 FOREACH_MOD OnUserQuit(user);
1847 WriteCommonExcept(user,"QUIT :%s",reason);
1849 // Q token must go to ALL servers!!!
1850 char buffer[MAXBUF];
1851 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1852 NetSendToAll(buffer);
1855 /* push the socket on a stack of sockets due to be closed at the next opportunity
1856 * 'Client exited' is an exception to this as it means the client side has already
1857 * closed the socket, we don't need to do it.
1859 fd_reap.push_back(user->fd);
1861 bool do_purge = false;
1863 if (user->registered == 7) {
1864 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1868 if (iter != clientlist.end())
1870 log(DEBUG,"deleting user hash value %d",iter->second);
1871 if ((iter->second) && (user->registered == 7)) {
1872 delete iter->second;
1874 clientlist.erase(iter);
1877 if (user->registered == 7) {
1878 purge_empty_chans();
1882 void kill_link_silent(userrec *user,const char* r)
1884 user_hash::iterator iter = clientlist.find(user->nick);
1886 char reason[MAXBUF];
1888 strncpy(reason,r,MAXBUF);
1890 if (strlen(reason)>MAXQUIT)
1892 reason[MAXQUIT-1] = '\0';
1895 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1896 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1897 log(DEBUG,"closing fd %d",user->fd);
1899 /* bugfix, cant close() a nonblocking socket (sux!) */
1900 if (user->registered == 7) {
1901 FOREACH_MOD OnUserQuit(user);
1902 WriteCommonExcept(user,"QUIT :%s",reason);
1904 // Q token must go to ALL servers!!!
1905 char buffer[MAXBUF];
1906 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1907 NetSendToAll(buffer);
1910 /* push the socket on a stack of sockets due to be closed at the next opportunity
1911 * 'Client exited' is an exception to this as it means the client side has already
1912 * closed the socket, we don't need to do it.
1914 fd_reap.push_back(user->fd);
1916 bool do_purge = false;
1918 if (iter != clientlist.end())
1920 log(DEBUG,"deleting user hash value %d",iter->second);
1921 if ((iter->second) && (user->registered == 7)) {
1922 delete iter->second;
1924 clientlist.erase(iter);
1927 if (user->registered == 7) {
1928 purge_empty_chans();
1934 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1936 char* Passwd(userrec *user)
1938 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1940 if (match(user->host,i->host) && (i->type == CC_ALLOW))
1948 bool IsDenied(userrec *user)
1950 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1952 if (match(user->host,i->host) && (i->type == CC_DENY))
1963 /* sends out an error notice to all connected clients (not to be used
1966 void send_error(char *s)
1968 log(DEBUG,"send_error: %s",s);
1969 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1971 if (isnick(i->second->nick))
1973 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
1977 // fix - unregistered connections receive ERROR, not NOTICE
1978 Write(i->second->fd,"ERROR :%s",s);
1983 void Error(int status)
1985 signal (SIGALRM, SIG_IGN);
1986 signal (SIGPIPE, SIG_IGN);
1987 signal (SIGTERM, SIG_IGN);
1988 signal (SIGABRT, SIG_IGN);
1989 signal (SIGSEGV, SIG_IGN);
1990 signal (SIGURG, SIG_IGN);
1991 signal (SIGKILL, SIG_IGN);
1992 log(DEBUG,"*** fell down a pothole in the road to perfection ***");
1993 send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
1998 int main(int argc, char *argv[])
2002 log(DEBUG,"*** InspIRCd starting up!");
2003 if (!FileExists(CONFIG_FILE))
2005 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2006 log(DEBUG,"main: no config");
2007 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2011 if (!strcmp(argv[1],"-nofork")) {
2015 if (InspIRCd() == ERROR)
2017 log(DEBUG,"main: daemon function bailed");
2018 printf("ERROR: could not initialise. Shutting down.\n");
2025 template<typename T> inline string ConvToStr(const T &in)
2028 if (!(tmp << in)) return string();
2032 /* re-allocates a nick in the user_hash after they change nicknames,
2033 * returns a pointer to the new user as it may have moved */
2035 userrec* ReHashNick(char* Old, char* New)
2037 user_hash::iterator newnick;
2038 user_hash::iterator oldnick = clientlist.find(Old);
2040 log(DEBUG,"ReHashNick: %s %s",Old,New);
2042 if (!strcasecmp(Old,New))
2044 log(DEBUG,"old nick is new nick, skipping");
2045 return oldnick->second;
2048 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2050 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2052 clientlist[New] = new userrec();
2053 clientlist[New] = oldnick->second;
2054 /*delete oldnick->second; */
2055 clientlist.erase(oldnick);
2057 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2059 return clientlist[New];
2062 /* adds or updates an entry in the whowas list */
2063 void AddWhoWas(userrec* u)
2065 user_hash::iterator iter = whowas.find(u->nick);
2066 userrec *a = new userrec();
2067 strcpy(a->nick,u->nick);
2068 strcpy(a->ident,u->ident);
2069 strcpy(a->dhost,u->dhost);
2070 strcpy(a->host,u->host);
2071 strcpy(a->fullname,u->fullname);
2072 strcpy(a->server,u->server);
2073 a->signon = u->signon;
2075 /* MAX_WHOWAS: max number of /WHOWAS items
2076 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2077 * can be replaced by a newer one
2080 if (iter == whowas.end())
2082 if (whowas.size() == WHOWAS_MAX)
2084 for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2086 // 3600 seconds in an hour ;)
2087 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
2091 log(DEBUG,"added WHOWAS entry, purged an old record");
2098 log(DEBUG,"added fresh WHOWAS entry");
2099 whowas[a->nick] = a;
2104 log(DEBUG,"updated WHOWAS entry");
2105 delete iter->second;
2111 /* add a client connection to the sockets list */
2112 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2116 char resolved[MAXBUF];
2119 user_hash::iterator iter;
2121 tempnick = ConvToStr(socket) + "-unknown";
2122 sprintf(tn2,"%d-unknown",socket);
2124 iter = clientlist.find(tempnick);
2126 if (iter != clientlist.end()) return;
2129 * It is OK to access the value here this way since we know
2130 * it exists, we just created it above.
2132 * At NO other time should you access a value in a map or a
2133 * hash_map this way.
2135 clientlist[tempnick] = new userrec();
2137 NonBlocking(socket);
2138 log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2140 clientlist[tempnick]->fd = socket;
2141 strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2142 strncpy(clientlist[tempnick]->host, host,160);
2143 strncpy(clientlist[tempnick]->dhost, host,160);
2144 strncpy(clientlist[tempnick]->server, ServerName,256);
2145 strncpy(clientlist[tempnick]->ident, "unknown",9);
2146 clientlist[tempnick]->registered = 0;
2147 clientlist[tempnick]->signon = time(NULL);
2148 clientlist[tempnick]->nping = time(NULL)+240;
2149 clientlist[tempnick]->lastping = 1;
2150 clientlist[tempnick]->port = port;
2151 strncpy(clientlist[tempnick]->ip,ip,32);
2155 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
2159 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
2162 // set the registration timeout for this user
2163 unsigned long class_regtimeout = 90;
2164 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2166 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2168 class_regtimeout = (unsigned long)i->registration_timeout;
2173 int class_flood = 0;
2174 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2176 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2178 class_flood = i->flood;
2183 clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
2184 clientlist[tempnick]->flood = class_flood;
2186 for (int i = 0; i < MAXCHANS; i++)
2188 clientlist[tempnick]->chans[i].channel = NULL;
2189 clientlist[tempnick]->chans[i].uc_modes = 0;
2192 if (clientlist.size() == MAXCLIENTS)
2193 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2195 char* r = matches_zline(ip);
2198 char reason[MAXBUF];
2199 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2200 kill_link(clientlist[tempnick],reason);
2207 return clientlist.size();
2211 int usercount_invisible(void)
2215 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2217 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2222 int usercount_opers(void)
2226 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2228 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2233 int usercount_unknown(void)
2237 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2239 if ((i->second->fd) && (i->second->registered != 7))
2245 long chancount(void)
2247 return chanlist.size();
2250 long count_servs(void)
2253 //for (int j = 0; j < 255; j++)
2255 // if (servers[j] != NULL)
2261 long servercount(void)
2263 return count_servs()+1;
2269 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2271 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2277 void ShowMOTD(userrec *user)
2281 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2284 WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
2285 for (int i = 0; i != MOTD.size(); i++)
2287 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
2289 WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
2292 void ShowRULES(userrec *user)
2296 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2299 WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2300 for (int i = 0; i != RULES.size(); i++)
2302 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2304 WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2307 /* shows the message of the day, and any other on-logon stuff */
2308 void ConnectUser(userrec *user)
2310 user->registered = 7;
2311 user->idle_lastmsg = time(NULL);
2312 log(DEBUG,"ConnectUser: %s",user->nick);
2314 if (strcmp(Passwd(user),"") && (!user->haspassed))
2316 kill_link(user,"Invalid password");
2321 kill_link(user,"Unauthorised connection");
2325 char match_against[MAXBUF];
2326 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2327 char* r = matches_gline(match_against);
2330 char reason[MAXBUF];
2331 snprintf(reason,MAXBUF,"G-Lined: %s",r);
2332 kill_link_silent(user,reason);
2336 r = matches_kline(user->host);
2339 char reason[MAXBUF];
2340 snprintf(reason,MAXBUF,"K-Lined: %s",r);
2341 kill_link_silent(user,reason);
2345 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2346 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2347 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2348 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2349 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2350 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);
2351 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);
2353 FOREACH_MOD OnUserConnect(user);
2354 WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
2356 char buffer[MAXBUF];
2357 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);
2358 NetSendToAll(buffer);
2361 void handle_version(char **parameters, int pcnt, userrec *user)
2363 char Revision[] = "$Revision$";
2365 char *s1 = Revision;
2367 char *v1 = strtok_r(s1," ",&savept);
2369 char *v2 = strtok_r(s1," ",&savept);
2372 WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2376 // calls a handler function for a command
2378 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2380 for (int i = 0; i < cmdlist.size(); i++)
2382 if (!strcasecmp(cmdlist[i].command,commandname))
2384 if (cmdlist[i].handler_function)
2386 if (pcnt>=cmdlist[i].min_params)
2388 if (strchr(user->modes,cmdlist[i].flags_needed))
2390 cmdlist[i].handler_function(parameters,pcnt,user);
2398 void DoSplitEveryone()
2400 bool go_again = true;
2404 for (int i = 0; i < 32; i++)
2408 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2410 if (strcasecmp(j->GetServerName().c_str(),ServerName))
2413 j->CloseConnection();
2414 me[i]->connectors.erase(j);
2422 log(DEBUG,"Removed server. Will remove clients...");
2423 // iterate through the userlist and remove all users on this server.
2424 // because we're dealing with a mesh, we dont have to deal with anything
2425 // "down-route" from this server (nice huh)
2427 char reason[MAXBUF];
2431 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2433 if (strcasecmp(u->second->server,ServerName))
2435 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2436 kill_link(u->second,reason);
2446 char islast(const char* s)
2449 for (int j = 0; j < 32; j++)
2453 for (int k = 0; k < me[j]->connectors.size(); k++)
2455 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2459 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2469 long map_count(const char* s)
2472 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2474 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2480 void force_nickchange(userrec* user,const char* newnick)
2487 FOREACH_RESULT(OnUserPreNick(user,newnick));
2489 kill_link(user,"Nickname collision");
2492 if (matches_qline(newnick))
2494 kill_link(user,"Nickname collision");
2502 strncpy(nick,newnick,MAXBUF);
2504 if (user->registered == 7)
2508 handle_nick(pars,1,user);
2514 int process_parameters(char **command_p,char *parameters)
2519 q = strlen(parameters);
2522 /* no parameters, command_p invalid! */
2525 if (parameters[0] == ':')
2527 command_p[0] = parameters+1;
2532 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2534 /* only one parameter */
2535 command_p[0] = parameters;
2536 if (parameters[0] == ':')
2538 if (strchr(parameters,' ') != NULL)
2546 command_p[j++] = parameters;
2547 for (int i = 0; i <= q; i++)
2549 if (parameters[i] == ' ')
2551 command_p[j++] = parameters+i+1;
2552 parameters[i] = '\0';
2553 if (command_p[j-1][0] == ':')
2555 *command_p[j-1]++; /* remove dodgy ":" */
2557 /* parameter like this marks end of the sequence */
2561 return j; /* returns total number of items in the list */
2564 void process_command(userrec *user, char* cmd)
2568 char *command_p[127];
2569 char p[MAXBUF], temp[MAXBUF];
2570 int i, j, items, cmd_found;
2572 for (int i = 0; i < 127; i++)
2573 command_p[i] = NULL;
2583 if (!strcmp(cmd,""))
2588 int total_params = 0;
2591 for (int q = 0; q < strlen(cmd)-1; q++)
2593 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2596 // found a 'trailing', we dont count them after this.
2604 // another phidjit bug...
2605 if (total_params > 126)
2607 //kill_link(user,"Protocol violation (1)");
2608 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2614 std::string tmp = cmd;
2615 for (int i = 0; i <= MODCOUNT; i++)
2617 std::string oldtmp = tmp;
2618 modules[i]->OnServerRaw(tmp,true,user);
2621 log(DEBUG,"A Module changed the input string!");
2622 log(DEBUG,"New string: %s",tmp.c_str());
2623 log(DEBUG,"Old string: %s",oldtmp.c_str());
2627 strncpy(cmd,tmp.c_str(),MAXBUF);
2630 if (!strchr(cmd,' '))
2632 /* no parameters, lets skip the formalities and not chop up
2634 log(DEBUG,"About to preprocess command with no params");
2636 command_p[0] = NULL;
2638 for (int i = 0; i <= strlen(cmd); i++)
2640 cmd[i] = toupper(cmd[i]);
2642 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2649 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2650 for (int i = 0; i < strlen(temp); i++)
2652 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2658 /* split the full string into a command plus parameters */
2662 if (strchr(cmd,' '))
2664 for (int i = 0; i <= strlen(cmd); i++)
2666 /* capitalise the command ONLY, leave params intact */
2667 cmd[i] = toupper(cmd[i]);
2668 /* are we nearly there yet?! :P */
2672 parameters = cmd+i+1;
2680 for (int i = 0; i <= strlen(cmd); i++)
2682 cmd[i] = toupper(cmd[i]);
2689 if (strlen(command)>MAXCOMMAND)
2691 //kill_link(user,"Protocol violation (2)");
2692 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2696 for (int x = 0; x < strlen(command); x++)
2698 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2700 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2702 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2704 //kill_link(user,"Protocol violation (3)");
2705 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2712 for (int i = 0; i != cmdlist.size(); i++)
2714 if (strcmp(cmdlist[i].command,""))
2716 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2718 log(DEBUG,"Found matching command");
2722 if (strcmp(parameters,""))
2724 items = process_parameters(command_p,parameters);
2729 command_p[0] = NULL;
2735 command_p[0] = NULL;
2740 log(DEBUG,"Processing command");
2742 /* activity resets the ping pending timer */
2743 user->nping = time(NULL) + 120;
2744 if ((items) < cmdlist[i].min_params)
2746 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2747 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2750 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2752 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2753 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2757 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2759 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2760 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2764 /* if the command isnt USER, PASS, or NICK, and nick is empty,
2766 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2768 if ((!isnick(user->nick)) || (user->registered != 7))
2770 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2771 WriteServ(user->fd,"451 %s :You have not registered",command);
2775 if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2777 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2778 if (cmdlist[i].handler_function)
2780 /* ikky /stats counters */
2785 user->bytes_in += strlen(temp);
2788 cmdlist[i].use_count++;
2789 cmdlist[i].total_bytes+=strlen(temp);
2792 /* WARNING: nothing may come after the
2793 * command handler call, as the handler
2794 * may free the user structure! */
2796 cmdlist[i].handler_function(command_p,items,user);
2802 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2803 WriteServ(user->fd,"451 %s :You have not registered",command);
2811 if ((!cmd_found) && (user))
2813 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
2814 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2819 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
2822 /* create the command and push it onto the table */
2823 strcpy(comm.command,cmd);
2824 comm.handler_function = f;
2825 comm.flags_needed = flags;
2826 comm.min_params = minparams;
2828 comm.total_bytes = 0;
2829 cmdlist.push_back(comm);
2830 log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
2833 void SetupCommandTable(void)
2835 createcommand("USER",handle_user,0,4);
2836 createcommand("NICK",handle_nick,0,1);
2837 createcommand("QUIT",handle_quit,0,0);
2838 createcommand("VERSION",handle_version,0,0);
2839 createcommand("PING",handle_ping,0,1);
2840 createcommand("PONG",handle_pong,0,1);
2841 createcommand("ADMIN",handle_admin,0,0);
2842 createcommand("PRIVMSG",handle_privmsg,0,2);
2843 createcommand("INFO",handle_info,0,0);
2844 createcommand("TIME",handle_time,0,0);
2845 createcommand("WHOIS",handle_whois,0,1);
2846 createcommand("WALLOPS",handle_wallops,'o',1);
2847 createcommand("NOTICE",handle_notice,0,2);
2848 createcommand("JOIN",handle_join,0,1);
2849 createcommand("NAMES",handle_names,0,1);
2850 createcommand("PART",handle_part,0,1);
2851 createcommand("KICK",handle_kick,0,2);
2852 createcommand("MODE",handle_mode,0,1);
2853 createcommand("TOPIC",handle_topic,0,1);
2854 createcommand("WHO",handle_who,0,1);
2855 createcommand("MOTD",handle_motd,0,0);
2856 createcommand("RULES",handle_rules,0,0);
2857 createcommand("OPER",handle_oper,0,2);
2858 createcommand("LIST",handle_list,0,0);
2859 createcommand("DIE",handle_die,'o',1);
2860 createcommand("RESTART",handle_restart,'o',1);
2861 createcommand("KILL",handle_kill,'o',2);
2862 createcommand("REHASH",handle_rehash,'o',0);
2863 createcommand("LUSERS",handle_lusers,0,0);
2864 createcommand("STATS",handle_stats,0,1);
2865 createcommand("USERHOST",handle_userhost,0,1);
2866 createcommand("AWAY",handle_away,0,0);
2867 createcommand("ISON",handle_ison,0,0);
2868 createcommand("SUMMON",handle_summon,0,0);
2869 createcommand("USERS",handle_users,0,0);
2870 createcommand("INVITE",handle_invite,0,2);
2871 createcommand("PASS",handle_pass,0,1);
2872 createcommand("TRACE",handle_trace,'o',0);
2873 createcommand("WHOWAS",handle_whowas,0,1);
2874 createcommand("CONNECT",handle_connect,'o',1);
2875 createcommand("SQUIT",handle_squit,'o',0);
2876 createcommand("MODULES",handle_modules,'o',0);
2877 createcommand("LINKS",handle_links,0,0);
2878 createcommand("MAP",handle_map,0,0);
2879 createcommand("KLINE",handle_kline,'o',1);
2880 createcommand("GLINE",handle_gline,'o',1);
2881 createcommand("ZLINE",handle_zline,'o',1);
2882 createcommand("QLINE",handle_qline,'o',1);
2885 void process_buffer(const char* cmdbuf,userrec *user)
2889 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2896 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2899 if (!strcmp(cmdbuf,""))
2903 while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
2905 strncpy(cmd,cmdbuf,MAXBUF);
2906 if (!strcmp(cmd,""))
2910 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2912 cmd[strlen(cmd)-1] = '\0';
2914 if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
2916 cmd[strlen(cmd)-1] = '\0';
2919 while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
2921 cmd[strlen(cmd)-1] = '\0';
2924 if (!strcmp(cmd,""))
2928 log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
2930 if ((user) && (cmd))
2932 process_command(user,cmd);
2936 void DoSync(serverrec* serv, char* tcp_host)
2939 log(DEBUG,"Sending sync");
2940 // send start of sync marker: Y <timestamp>
2941 // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2942 // except the ones its receiving it from.
2943 snprintf(data,MAXBUF,"Y %d",time(NULL));
2944 serv->SendPacket(data,tcp_host);
2945 // send users and channels
2946 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2948 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);
2949 serv->SendPacket(data,tcp_host);
2950 for (int i = 0; i <= MODCOUNT; i++)
2952 string_list l = modules[i]->OnUserSync(u->second);
2953 for (int j = 0; j < l.size(); j++)
2955 strncpy(data,l[j].c_str(),MAXBUF);
2956 serv->SendPacket(data,tcp_host);
2959 if (strcmp(chlist(u->second),""))
2961 snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
2962 serv->SendPacket(data,tcp_host);
2965 // send channel modes, topics etc...
2966 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2968 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2969 serv->SendPacket(data,tcp_host);
2970 for (int i = 0; i <= MODCOUNT; i++)
2972 string_list l = modules[i]->OnChannelSync(c->second);
2973 for (int j = 0; j < l.size(); j++)
2975 strncpy(data,l[j].c_str(),MAXBUF);
2976 serv->SendPacket(data,tcp_host);
2979 if (strcmp(c->second->topic,""))
2981 snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2982 serv->SendPacket(data,tcp_host);
2984 // send current banlist
2986 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2988 snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
2989 serv->SendPacket(data,tcp_host);
2992 // sync global zlines, glines, etc
2993 sync_xlines(serv,tcp_host);
2994 snprintf(data,MAXBUF,"F %d",time(NULL));
2995 serv->SendPacket(data,tcp_host);
2996 log(DEBUG,"Sent sync");
2997 // ircd sends its serverlist after the end of sync here
3001 void NetSendMyRoutingTable()
3003 // send out a line saying what is reachable to us.
3004 // E.g. if A is linked to B C and D, send out:
3006 // if its only linked to B and D send out:
3008 // if it has no links, dont even send out the line at all.
3009 char buffer[MAXBUF];
3010 sprintf(buffer,"$ %s",ServerName);
3011 bool sendit = false;
3012 for (int i = 0; i < 32; i++)
3016 for (int j = 0; j < me[i]->connectors.size(); j++)
3018 if (me[i]->connectors[j].GetState() != STATE_DISCONNECTED)
3020 strncat(buffer," ",MAXBUF);
3021 strncat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3028 NetSendToAll(buffer);
3032 void DoSplit(const char* params)
3034 bool go_again = true;
3038 for (int i = 0; i < 32; i++)
3042 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3044 if (!strcasecmp(j->GetServerName().c_str(),params))
3047 j->CloseConnection();
3048 me[i]->connectors.erase(j);
3056 log(DEBUG,"Removed server. Will remove clients...");
3057 // iterate through the userlist and remove all users on this server.
3058 // because we're dealing with a mesh, we dont have to deal with anything
3059 // "down-route" from this server (nice huh)
3061 char reason[MAXBUF];
3062 snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3066 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3068 if (!strcasecmp(u->second->server,params))
3070 kill_link(u->second,reason);
3078 // removes a server. Will NOT remove its users!
3080 void RemoveServer(const char* name)
3082 bool go_again = true;
3086 for (int i = 0; i < 32; i++)
3090 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3092 if (!strcasecmp(j->GetServerName().c_str(),name))
3095 j->CloseConnection();
3096 me[i]->connectors.erase(j);
3107 int reap_counter = 0;
3111 struct sockaddr_in client, server;
3112 char addrs[MAXBUF][255];
3113 int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
3115 int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
3116 int selectResult = 0, selectResult2 = 0;
3117 char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3118 char resolvedHost[MAXBUF];
3122 log_file = fopen("ircd.log","a+");
3125 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3129 log(DEBUG,"InspIRCd: startup: begin");
3133 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3135 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
3137 SetupCommandTable();
3138 log(DEBUG,"InspIRCd: startup: default command table set up");
3141 if (strcmp(DieValue,""))
3143 printf("WARNING: %s\n\n",DieValue);
3146 log(DEBUG,"InspIRCd: startup: read config");
3148 int count2 = 0, count3 = 0;
3150 for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3152 ConfValue("bind","port",count,configToken,&config_f);
3153 ConfValue("bind","address",count,Addr,&config_f);
3154 ConfValue("bind","type",count,Type,&config_f);
3155 if (!strcmp(Type,"servers"))
3157 char Default[MAXBUF];
3158 strcpy(Default,"no");
3159 ConfValue("bind","default",count,Default,&config_f);
3160 if (strchr(Default,'y'))
3162 defaultRoute = count3;
3163 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3165 me[count3] = new serverrec(ServerName,100L,false);
3166 me[count3]->CreateListener(Addr,atoi(configToken));
3171 ports[count2] = atoi(configToken);
3172 strcpy(addrs[count2],Addr);
3175 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3178 UDPportCount = count3;
3180 log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3182 log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3186 /* BugFix By Craig! :p */
3188 for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3190 char modfile[MAXBUF];
3191 ConfValue("module","name",count2,configToken,&config_f);
3192 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
3193 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
3194 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
3195 /* If The File Doesnt exist, Trying to load it
3196 * Will Segfault the IRCd.. So, check to see if
3197 * it Exists, Before Proceeding. */
3198 if (FileExists(modfile))
3200 factory[count] = new ircd_module(modfile);
3201 if (factory[count]->LastError())
3203 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
3204 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
3207 if (factory[count]->factory)
3209 modules[count] = factory[count]->factory->CreateModule();
3210 /* save the module and the module's classfactory, if
3211 * this isnt done, random crashes can occur :/ */
3212 module_names.push_back(modfile);
3216 log(DEBUG,"Unable to load %s",modfile);
3217 sprintf("Unable to load %s\nExiting...\n",modfile);
3220 /* Increase the Count */
3225 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
3226 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
3229 MODCOUNT = count - 1;
3230 log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3232 printf("\nInspIRCd is now running!\n");
3234 startup_time = time(NULL);
3238 log(VERBOSE,"Not forking as -nofork was specified");
3242 if (DaemonSeed() == ERROR)
3244 log(DEBUG,"InspIRCd: startup: can't daemonise");
3245 printf("ERROR: could not go into daemon mode. Shutting down.\n");
3251 /* setup select call */
3252 FD_ZERO(&selectFds);
3253 log(DEBUG,"InspIRCd: startup: zero selects");
3254 log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3256 for (count = 0; count < portCount; count++)
3258 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3260 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3263 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3265 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
3267 else /* well we at least bound to one socket so we'll continue */
3273 log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3275 /* if we didn't bind to anything then abort */
3276 if (boundPortCount == 0)
3278 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
3283 length = sizeof (client);
3284 char udp_msg[MAXBUF], tcp_host[MAXBUF];
3286 /* main loop, this never returns */
3289 #ifdef _POSIX_PRIORITY_SCHEDULING
3292 // update the status of klines, etc
3299 user_hash::iterator count2 = clientlist.begin();
3301 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3302 // them in a list, then reap the list every second or so.
3303 if (reap_counter>300)
3305 if (fd_reap.size() > 0)
3307 for( int n = 0; n < fd_reap.size(); n++)
3309 Blocking(fd_reap[n]);
3311 NonBlocking(fd_reap[n]);
3320 FD_ZERO(&serverfds);
3323 for (int x = 0; x != UDPportCount; x++)
3325 FD_SET(me[x]->fd, &serverfds);
3331 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3334 for (int x = 0; x != UDPportCount; x++)
3336 if (FD_ISSET (me[x]->fd, &serverfds))
3338 char remotehost[MAXBUF],resolved[MAXBUF];
3339 length = sizeof (client);
3340 incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3341 strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3342 if(CleanAndResolve(resolved, remotehost) != TRUE)
3344 strncpy(resolved,remotehost,MAXBUF);
3346 // add to this connections ircd_connector vector
3347 // *FIX* - we need the LOCAL port not the remote port in &client!
3348 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3353 for (int x = 0; x < UDPportCount; x++)
3355 std::deque<std::string> msgs;
3357 if (me[x]->RecvPacket(msgs, tcp_host))
3359 for (int ctr = 0; ctr < msgs.size(); ctr++)
3361 char udp_msg[MAXBUF];
3362 strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3363 if (strlen(udp_msg)<1)
3365 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3368 // during a netburst, send all data to all other linked servers
3369 if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3371 if (is_uline(tcp_host))
3373 if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3375 NetSendToAllExcept(tcp_host,udp_msg);
3379 NetSendToAllExcept(tcp_host,udp_msg);
3381 FOREACH_MOD OnPacketReceive(udp_msg);
3382 handle_link_packet(udp_msg, tcp_host, me[x]);
3389 while (count2 != clientlist.end())
3392 tval.tv_usec = tval.tv_sec = 0;
3394 int total_in_this_set = 0;
3396 user_hash::iterator xcount = count2;
3397 user_hash::iterator endingiter = count2;
3399 if (!count2->second) break;
3402 if (count2->second->fd != 0)
3404 // assemble up to 64 sockets into an fd_set
3405 // to implement a pooling mechanism.
3407 // This should be up to 64x faster than the
3408 // old implementation.
3409 while (total_in_this_set < 64)
3411 if (count2 != clientlist.end())
3413 // we don't check the state of remote users.
3414 if (count2->second->fd > 0)
3416 FD_SET (count2->second->fd, &sfd);
3418 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3419 // their connection class.
3420 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7))
3422 log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3423 kill_link(count2->second,"Registration timeout");
3426 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3428 if ((!count2->second->lastping) && (count2->second->registered == 7))
3430 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3431 kill_link(count2->second,"Ping timeout");
3434 Write(count2->second->fd,"PING :%s",ServerName);
3435 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3436 count2->second->lastping = 0;
3437 count2->second->nping = time(NULL)+120;
3441 total_in_this_set++;
3446 endingiter = count2;
3447 count2 = xcount; // roll back to where we were
3453 selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3455 // now loop through all of the items in this pool if any are waiting
3456 //if (selectResult2 > 0)
3457 for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3460 #ifdef _POSIX_PRIORITY_SCHEDULING
3465 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3467 log(DEBUG,"Reading fd %d",count2a->second->fd);
3468 memset(data, 0, 10240);
3469 result = read(count2a->second->fd, data, 10240);
3474 log(DEBUG,"Read %d characters from socket",result);
3475 userrec* current = count2a->second;
3476 int currfd = current->fd;
3477 char* l = strtok(data,"\n");
3482 if ((floodlines > current->flood) && (current->flood != 0))
3484 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3485 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3486 kill_link(current,"Excess flood");
3489 char sanitized[NetBufferSize];
3490 memset(sanitized, 0, NetBufferSize);
3492 for (int pt = 0; pt < strlen(l); pt++)
3496 sanitized[ptt++] = l[pt];
3499 sanitized[ptt] = '\0';
3500 if (strlen(sanitized))
3504 // we're gonna re-scan to check if the nick is gone, after every
3505 // command - if it has, we're gonna bail
3506 bool find_again = false;
3507 process_buffer(sanitized,current);
3509 // look for the user's record in case it's changed
3510 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3512 if (c2->second->fd == currfd)
3514 // found again, update pointer
3515 current == c2->second;
3524 l = strtok(NULL,"\n");
3529 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3531 log(DEBUG,"killing: %s",count2a->second->nick);
3532 kill_link(count2a->second,strerror(errno));
3536 // result EAGAIN means nothing read
3537 if (result == EAGAIN)
3545 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3546 kill_link(count2a->second,"Client exited");
3547 // must bail here? kill_link removes the hash, corrupting the iterator
3548 log(DEBUG,"Bailing from client exit");
3552 else if (result > 0)
3557 for (int q = 0; q < total_in_this_set; q++)
3559 // there is no iterator += operator :(
3560 //if (count2 != clientlist.end())
3567 // set up select call
3568 for (count = 0; count < boundPortCount; count++)
3570 FD_SET (openSockfd[count], &selectFds);
3574 selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3576 /* select is reporting a waiting socket. Poll them all to find out which */
3577 if (selectResult > 0)
3579 char target[MAXBUF], resolved[MAXBUF];
3580 for (count = 0; count < boundPortCount; count++)
3582 if (FD_ISSET (openSockfd[count], &selectFds))
3584 length = sizeof (client);
3585 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3587 address_cache::iterator iter = IP.find(client.sin_addr);
3588 bool iscached = false;
3589 if (iter == IP.end())
3591 /* ip isn't in cache, add it */
3592 strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3593 if(CleanAndResolve(resolved, target) != TRUE)
3595 strncpy(resolved,target,MAXBUF);
3597 /* hostname now in 'target' */
3598 IP[client.sin_addr] = new string(resolved);
3599 /* hostname in cache */
3603 /* found ip (cached) */
3604 strncpy(resolved, iter->second->c_str(), MAXBUF);
3608 if (incomingSockfd < 0)
3610 WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
3611 log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
3615 AddClient(incomingSockfd, resolved, ports[count], iscached, inet_ntoa (client.sin_addr));
3616 log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
3623 if(0) {}; // "Label must be followed by a statement"... so i gave it one.
3626 close (incomingSockfd);