1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 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 * ---------------------------------------------------
18 #include "inspircd_config.h"
20 #include "configreader.h"
23 #include <sys/errno.h>
31 #include "connection.h"
42 #include "inspstring.h"
43 #include "helperfuncs.h"
48 extern ModuleList modules;
49 extern InspIRCd* ServerInstance;
51 extern char lowermap[255];
52 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
53 extern std::vector<userrec*> all_opers;
54 extern user_hash clientlist;
55 extern chan_hash chanlist;
57 char LOG_FILE[MAXBUF];
59 extern std::vector<userrec*> local_users;
61 static char TIMESTR[26];
62 static time_t LAST = 0;
65 * Write a line of text `text' to the logfile (and stdout, if in nofork) if the level `level'
66 * is greater than the configured loglevel.
68 void InspIRCd::Log(int level, const char* text, ...)
71 char textbuffer[MAXBUF];
73 va_start(argsPtr, text);
74 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
77 InspIRCd::Log(level, std::string(textbuffer));
80 void InspIRCd::Log(int level, const std::string &text)
82 if (!ServerInstance || !ServerInstance->Config)
85 /* If we were given -debug we output all messages, regardless of configured loglevel */
86 if ((level < ServerInstance->Config->LogLevel) && !ServerInstance->Config->forcedebug)
91 struct tm *timeinfo = localtime(&TIME);
93 strlcpy(TIMESTR,asctime(timeinfo),26);
98 if (ServerInstance->Config->log_file && ServerInstance->Config->writelog)
100 fprintf(ServerInstance->Config->log_file,"%s %s\n",TIMESTR,text.c_str());
101 fflush(ServerInstance->Config->log_file);
104 if (ServerInstance->Config->nofork)
106 printf("%s %s\n", TIMESTR, text.c_str());
111 * Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
113 * XXX - we may want to consider returning a file_cache or pointer to one, less confusing.
115 void readfile(file_cache &F, const char* fname)
118 char linebuf[MAXBUF];
120 log(DEBUG,"readfile: loading %s",fname);
122 file = fopen(fname,"r");
128 fgets(linebuf,sizeof(linebuf),file);
129 linebuf[strlen(linebuf)-1]='\0';
138 F.push_back(linebuf);
146 log(DEBUG,"readfile: failed to load file: %s",fname);
149 log(DEBUG,"readfile: loaded %s, %lu lines",fname,(unsigned long)F.size());
153 std::string GetServerDescription(const char* servername)
155 std::string description = "";
157 FOREACH_MOD(I_OnGetServerDescription,OnGetServerDescription(servername,description));
159 if (description != "")
165 // not a remote server that can be found, it must be me.
166 return ServerInstance->Config->ServerDesc;
170 /* XXX - We don't use WriteMode for this because WriteMode is very slow and
171 * this isnt. Basically WriteMode has to iterate ALL the users 'n' times for
172 * the number of modes provided, e.g. if you send WriteMode 'og' to write to
173 * opers with globops, and you have 2000 users, thats 4000 iterations. WriteOpers
174 * uses the oper list, which means if you have 2000 users but only 5 opers,
175 * it iterates 5 times.
177 void WriteOpers(const char* text, ...)
179 char textbuffer[MAXBUF];
184 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
188 va_start(argsPtr, text);
189 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
192 WriteOpers_NoFormat(textbuffer);
195 void WriteOpers_NoFormat(const char* text)
199 log(DEFAULT,"*** BUG *** WriteOpers_NoFormat was given an invalid parameter");
203 for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
209 if (a->modes[UM_SERVERNOTICE])
211 // send server notices to all with +s
212 a->WriteServ("NOTICE %s :%s",a->nick,text);
218 void ServerNoticeAll(char* text, ...)
223 char textbuffer[MAXBUF];
224 char formatbuffer[MAXBUF];
226 va_start (argsPtr, text);
227 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
230 snprintf(formatbuffer,MAXBUF,"NOTICE $%s :%s",ServerInstance->Config->ServerName,textbuffer);
232 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
235 t->WriteServ(std::string(formatbuffer));
239 void ServerPrivmsgAll(char* text, ...)
244 char textbuffer[MAXBUF];
245 char formatbuffer[MAXBUF];
247 va_start (argsPtr, text);
248 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
251 snprintf(formatbuffer,MAXBUF,"PRIVMSG $%s :%s",ServerInstance->Config->ServerName,textbuffer);
253 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
256 t->WriteServ(std::string(formatbuffer));
260 void WriteMode(const char* modes, int flags, const char* text, ...)
262 char textbuffer[MAXBUF];
266 if ((!text) || (!modes) || (!flags))
268 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
272 va_start(argsPtr, text);
273 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
275 modelen = strlen(modes);
277 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
279 userrec* t = (userrec*)(*i);
280 bool send_to_user = false;
286 for (int n = 0; n < modelen; n++)
288 if (!t->modes[modes[n]-65])
290 send_to_user = false;
295 else if (flags == WM_OR)
297 send_to_user = false;
299 for (int n = 0; n < modelen; n++)
301 if (t->modes[modes[n]-65])
311 t->WriteServ("NOTICE %s :%s",t->nick,textbuffer);
316 void NoticeAll(userrec *source, bool local_only, char* text, ...)
318 char textbuffer[MAXBUF];
319 char formatbuffer[MAXBUF];
322 if ((!text) || (!source))
324 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
328 va_start(argsPtr, text);
329 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
332 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
334 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
337 t->WriteFrom(source,std::string(formatbuffer));
342 /* convert a string to lowercase. Note following special circumstances
343 * taken from RFC 1459. Many "official" server branches still hold to this
344 * rule so i will too;
346 * Because of IRC's scandanavian origin, the characters {}| are
347 * considered to be the lower case equivalents of the characters []\,
348 * respectively. This is a critical issue when determining the
349 * equivalence of two nicknames.
351 void strlower(char *n)
355 for (char* t = n; *t; t++)
356 *t = lowermap[(unsigned char)*t];
360 /* Find a user record by nickname and return a pointer to it */
362 userrec* Find(const std::string &nick)
364 user_hash::iterator iter = clientlist.find(nick);
366 if (iter == clientlist.end())
367 /* Couldn't find it */
373 userrec* Find(const char* nick)
375 user_hash::iterator iter;
380 iter = clientlist.find(nick);
382 if (iter == clientlist.end())
388 /* find a channel record by channel name and return a pointer to it */
390 chanrec* FindChan(const char* chan)
392 chan_hash::iterator iter;
396 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
400 iter = chanlist.find(chan);
402 if (iter == chanlist.end())
403 /* Couldn't find it */
410 long GetMaxBans(char* name)
413 for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
416 if (match(name,x.c_str()))
424 void purge_empty_chans(userrec* u)
426 std::vector<chanrec*> to_delete;
428 // firstly decrement the count on each channel
429 for (std::vector<ucrec*>::iterator f = u->chans.begin(); f != u->chans.end(); f++)
431 ucrec* uc = (ucrec*)(*f);
434 if (uc->channel->DelUser(u) == 0)
436 /* No users left in here, mark it for deletion */
437 to_delete.push_back(uc->channel);
443 log(DEBUG,"purge_empty_chans: %d channels to delete",to_delete.size());
445 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
447 chanrec* thischan = (chanrec*)*n;
448 chan_hash::iterator i2 = chanlist.find(thischan->name);
449 if (i2 != chanlist.end())
451 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
461 char* chanmodes(chanrec *chan, bool showkey)
463 static char scratch[MAXBUF];
464 static char sparam[MAXBUF];
465 char* offset = scratch;
466 std::string extparam = "";
470 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
478 /* This was still iterating up to 190, chanrec::custom_modes is only 64 elements -- Om */
479 for(int n = 0; n < 64; n++)
488 extparam = (showkey ? chan->key : "<key>");
491 extparam = ConvToStr(chan->limit);
499 /* We know these have no parameters */
502 extparam = chan->GetModeParameter(n+65);
507 charlcat(sparam,' ',MAXBUF);
508 strlcat(sparam,extparam.c_str(),MAXBUF);
513 /* Null terminate scratch */
515 strlcat(scratch,sparam,MAXBUF);
520 /* compile a userlist of a channel into a string, each nick seperated by
521 * spaces and op, voice etc status shown as @ and + */
523 void userlist(userrec *user,chanrec *c)
527 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
534 dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
537 char* ptr = list + dlen;
539 CUList *ulist= c->GetUsers();
541 /* Improvement by Brain - this doesnt change in value, so why was it inside
544 bool has_user = c->HasUser(user);
546 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
548 if ((!has_user) && (i->second->modes[UM_INVISIBLE]))
551 * user is +i, and source not on the channel, does not show
557 size_t ptrlen = snprintf(ptr, MAXBUF, "%s%s ", cmode(i->second, c), i->second->nick);
564 if (curlen > (480-NICKMAX))
566 /* list overflowed into multiple numerics */
567 user->WriteServ(list);
569 /* reset our lengths */
570 dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
578 /* if whats left in the list isnt empty, send it */
581 user->WriteServ(list);
586 * return a count of the users on a specific channel accounting for
587 * invisible users who won't increase the count. e.g. for /LIST
589 int usercount_i(chanrec *c)
596 CUList *ulist= c->GetUsers();
597 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
599 if (!(i->second->modes[UM_INVISIBLE]))
606 int usercount(chanrec *c)
608 return (c ? c->GetUserCounter() : 0);
612 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
613 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
614 * then their ip will be taken as 'priority' anyway, so for example,
615 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
617 ConnectClass GetClass(userrec *user)
619 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
621 if ((match(user->GetIPString(),i->host.c_str(),true)) || (match(user->host,i->host.c_str())))
627 return *(ServerInstance->Config->Classes.begin());
631 * sends out an error notice to all connected clients (not to be used
634 void send_error(char *s)
636 log(DEBUG,"send_error: %s",s);
638 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
640 userrec* t = (userrec*)(*i);
641 if (t->registered == REG_ALL)
643 t->WriteServ("NOTICE %s :%s",t->nick,s);
647 // fix - unregistered connections receive ERROR, not NOTICE
648 t->Write("ERROR :%s",s);
653 void Error(int status)
659 signal(SIGALRM, SIG_IGN);
660 signal(SIGPIPE, SIG_IGN);
661 signal(SIGTERM, SIG_IGN);
662 signal(SIGABRT, SIG_IGN);
663 signal(SIGSEGV, SIG_IGN);
664 signal(SIGURG, SIG_IGN);
665 signal(SIGKILL, SIG_IGN);
666 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
668 log(DEFAULT,"Please report the backtrace lines shown below with any bugreport to the bugtracker at http://www.inspircd.org/bugtrack/");
669 size = backtrace(array, 30);
670 strings = backtrace_symbols(array, size);
671 for (size_t i = 0; i < size; i++) {
672 log(DEFAULT,"[%d] %s", i, strings[i]);
675 WriteOpers("*** SIGSEGV: Please see the ircd.log for backtrace and report the error to http://www.inspircd.org/bugtrack/");
677 log(DEFAULT,"You do not have execinfo.h so i could not backtrace -- on FreeBSD, please install the libexecinfo port.");
679 send_error("Somebody screwed up... Whoops. IRC Server terminating.");
680 signal(SIGSEGV, SIG_DFL);
681 if (raise(SIGSEGV) == -1)
683 log(DEFAULT,"What the hell, i couldnt re-raise SIGSEGV! Error: %s",strerror(errno));
688 // this function counts all users connected, wether they are registered or NOT.
691 return clientlist.size();
694 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
695 int registered_usercount(void)
699 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
701 c += (i->second->registered == REG_ALL);
707 int usercount_invisible(void)
711 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
713 c += ((i->second->registered == REG_ALL) && (i->second->modes[UM_INVISIBLE]));
719 int usercount_opers(void)
723 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
725 if (*(i->second->oper))
731 int usercount_unknown(void)
735 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
737 userrec* t = (userrec*)(*i);
738 if (t->registered != REG_ALL)
747 return chanlist.size();
754 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
756 userrec* t = (userrec*)(*i);
757 if (t->registered == REG_ALL)
764 void ShowMOTD(userrec *user)
766 if (!ServerInstance->Config->MOTD.size())
768 user->WriteServ("422 %s :Message of the day file is missing.",user->nick);
771 user->WriteServ("375 %s :%s message of the day", user->nick, ServerInstance->Config->ServerName);
773 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
774 user->WriteServ("372 %s :- %s",user->nick,ServerInstance->Config->MOTD[i].c_str());
776 user->WriteServ("376 %s :End of message of the day.", user->nick);
779 void ShowRULES(userrec *user)
781 if (!ServerInstance->Config->RULES.size())
783 user->WriteServ("NOTICE %s :Rules file is missing.",user->nick);
786 user->WriteServ("NOTICE %s :%s rules",user->nick,ServerInstance->Config->ServerName);
788 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
789 user->WriteServ("NOTICE %s :%s",user->nick,ServerInstance->Config->RULES[i].c_str());
791 user->WriteServ("NOTICE %s :End of %s rules.",user->nick,ServerInstance->Config->ServerName);
794 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
795 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
796 // registration timeout maximum seconds)
797 bool AllModulesReportReady(userrec* user)
799 if (!ServerInstance->Config->global_implementation[I_OnCheckReady])
802 for (int i = 0; i <= MODCOUNT; i++)
804 if (ServerInstance->Config->implement_lists[i][I_OnCheckReady])
806 int res = modules[i]->OnCheckReady(user);
815 /* Make Sure Modules Are Avaliable!
816 * (BugFix By Craig.. See? I do work! :p)
817 * Modified by brain, requires const char*
818 * to work with other API functions
822 bool FileExists (const char* file)
825 if ((input = fopen (file, "r")) == NULL)
836 char* CleanFilename(char* name)
838 char* p = name + strlen(name);
839 while ((p != name) && (*p != '/')) p--;
840 return (p != name ? ++p : p);
843 bool DirValid(char* dirandfile)
847 char otherdir[MAXBUF];
850 strlcpy(work, dirandfile, MAXBUF);
853 // we just want the dir
865 // Get the current working directory
866 if (getcwd(buffer, MAXBUF ) == NULL )
871 if (getcwd(otherdir, MAXBUF ) == NULL )
876 size_t t = strlen(work);
878 if (strlen(otherdir) >= t)
882 if (!strcmp(otherdir,work))
895 std::string GetFullProgDir(char** argv, int argc)
899 char otherdir[MAXBUF];
902 strlcpy(work,argv[0],MAXBUF);
905 // we just want the dir
917 // Get the current working directory
918 if (getcwd(buffer, MAXBUF) == NULL)
923 if (getcwd(otherdir, MAXBUF) == NULL)
930 int InsertMode(std::string &output, const char* mode, unsigned short section)
932 unsigned short currsection = 1;
933 unsigned int pos = output.find("CHANMODES=", 0) + 10; // +10 for the length of "CHANMODES="
935 if(section > 4 || section == 0)
937 log(DEBUG, "InsertMode: CHANMODES doesn't have a section %dh :/", section);
941 for(; pos < output.size(); pos++)
943 if(section == currsection)
946 if(output[pos] == ',')
950 output.insert(pos, mode);
954 bool IsValidChannelName(const char *chname)
958 /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
959 if (!chname || *chname != '#')
964 c = (char *)chname + 1;
978 /* too long a name - note funky pointer arithmetic here. */
979 if ((c - chname) > CHANMAX)
987 inline int charlcat(char* x,char y,int z)
1004 bool charremove(char* mp, char remove)
1007 bool shift_down = false;
1011 if (*mptr == remove)
1023 void OpenLog(char** argv, int argc)
1027 if (ServerInstance->Config->logpath == "")
1029 ServerInstance->Config->logpath = GetFullProgDir(argv,argc) + "/ircd.log";
1034 ServerInstance->Config->log_file = fopen(LOG_FILE,"a+");
1036 if (!ServerInstance->Config->log_file)
1038 printf("ERROR: Could not write to logfile %s, bailing!\n\n",ServerInstance->Config->logpath.c_str());
1045 ServerInstance->Config->log_file = fopen(ServerInstance->Config->logpath.c_str(),"a+");
1047 if (!ServerInstance->Config->log_file)
1049 printf("ERROR: Could not write to logfile %s, bailing!\n\n",ServerInstance->Config->logpath.c_str());
1058 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
1059 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
1066 if (*ServerInstance->Config->DieValue)
1068 printf("WARNING: %s\n\n",ServerInstance->Config->DieValue);
1069 log(DEFAULT,"Uh-Oh, somebody didn't read their config file: '%s'",ServerInstance->Config->DieValue);
1074 /* We must load the modules AFTER initializing the socket engine, now */
1075 void LoadAllModules(InspIRCd* ServerInstance)
1077 char configToken[MAXBUF];
1078 ServerInstance->Config->module_names.clear();
1081 for (int count = 0; count < ServerInstance->Config->ConfValueEnum(ServerInstance->Config->config_data, "module"); count++)
1083 ServerInstance->Config->ConfValue(ServerInstance->Config->config_data, "module","name",count,configToken,MAXBUF);
1084 printf("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
1086 if (!ServerInstance->LoadModule(configToken))
1088 log(DEFAULT,"Exiting due to a module loader error.");
1089 printf("\nThere was an error loading a module: %s\n\n",ServerInstance->ModuleError());
1094 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);