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 ServerConfig *Config;
50 extern InspIRCd* ServerInstance;
52 extern char lowermap[255];
53 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
54 extern std::vector<userrec*> all_opers;
55 extern user_hash clientlist;
56 extern chan_hash chanlist;
58 char LOG_FILE[MAXBUF];
60 extern std::vector<userrec*> local_users;
62 static char TIMESTR[26];
63 static time_t LAST = 0;
66 * Write a line of text `text' to the logfile (and stdout, if in nofork) if the level `level'
67 * is greater than the configured loglevel.
69 void do_log(int level, const char *text, ...)
72 char textbuffer[MAXBUF];
74 /* If we were given -debug we output all messages, regardless of configured loglevel */
75 if ((level < Config->LogLevel) && !Config->forcedebug)
80 struct tm *timeinfo = localtime(&TIME);
82 strlcpy(TIMESTR,asctime(timeinfo),26);
89 va_start(argsPtr, text);
90 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
95 fprintf(Config->log_file,"%s %s\n",TIMESTR,textbuffer);
96 fflush(Config->log_file);
102 printf("%s %s\n", TIMESTR, textbuffer);
107 * Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
109 * XXX - we may want to consider returning a file_cache or pointer to one, less confusing.
111 void readfile(file_cache &F, const char* fname)
114 char linebuf[MAXBUF];
116 log(DEBUG,"readfile: loading %s",fname);
118 file = fopen(fname,"r");
124 fgets(linebuf,sizeof(linebuf),file);
125 linebuf[strlen(linebuf)-1]='\0';
134 F.push_back(linebuf);
142 log(DEBUG,"readfile: failed to load file: %s",fname);
145 log(DEBUG,"readfile: loaded %s, %lu lines",fname,(unsigned long)F.size());
149 std::string GetServerDescription(const char* servername)
151 std::string description = "";
153 FOREACH_MOD(I_OnGetServerDescription,OnGetServerDescription(servername,description));
155 if (description != "")
161 // not a remote server that can be found, it must be me.
162 return Config->ServerDesc;
166 /* XXX - We don't use WriteMode for this because WriteMode is very slow and
167 * this isnt. Basically WriteMode has to iterate ALL the users 'n' times for
168 * the number of modes provided, e.g. if you send WriteMode 'og' to write to
169 * opers with globops, and you have 2000 users, thats 4000 iterations. WriteOpers
170 * uses the oper list, which means if you have 2000 users but only 5 opers,
171 * it iterates 5 times.
173 void WriteOpers(const char* text, ...)
175 char textbuffer[MAXBUF];
180 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
184 va_start(argsPtr, text);
185 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
188 WriteOpers_NoFormat(textbuffer);
191 void WriteOpers_NoFormat(const char* text)
195 log(DEFAULT,"*** BUG *** WriteOpers_NoFormat was given an invalid parameter");
199 for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
205 if (a->modes[UM_SERVERNOTICE])
207 // send server notices to all with +s
208 a->WriteServ("NOTICE %s :%s",a->nick,text);
214 void ServerNoticeAll(char* text, ...)
219 char textbuffer[MAXBUF];
220 char formatbuffer[MAXBUF];
222 va_start (argsPtr, text);
223 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
226 snprintf(formatbuffer,MAXBUF,"NOTICE $%s :%s",Config->ServerName,textbuffer);
228 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
231 t->WriteServ(std::string(formatbuffer));
235 void ServerPrivmsgAll(char* text, ...)
240 char textbuffer[MAXBUF];
241 char formatbuffer[MAXBUF];
243 va_start (argsPtr, text);
244 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
247 snprintf(formatbuffer,MAXBUF,"PRIVMSG $%s :%s",Config->ServerName,textbuffer);
249 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
252 t->WriteServ(std::string(formatbuffer));
256 void WriteMode(const char* modes, int flags, const char* text, ...)
258 char textbuffer[MAXBUF];
262 if ((!text) || (!modes) || (!flags))
264 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
268 va_start(argsPtr, text);
269 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
271 modelen = strlen(modes);
273 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
275 userrec* t = (userrec*)(*i);
276 bool send_to_user = false;
282 for (int n = 0; n < modelen; n++)
284 if (!t->modes[modes[n]-65])
286 send_to_user = false;
291 else if (flags == WM_OR)
293 send_to_user = false;
295 for (int n = 0; n < modelen; n++)
297 if (t->modes[modes[n]-65])
307 t->WriteServ("NOTICE %s :%s",t->nick,textbuffer);
312 void NoticeAll(userrec *source, bool local_only, char* text, ...)
314 char textbuffer[MAXBUF];
315 char formatbuffer[MAXBUF];
318 if ((!text) || (!source))
320 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
324 va_start(argsPtr, text);
325 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
328 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
330 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
333 t->WriteFrom(source,std::string(formatbuffer));
338 /* convert a string to lowercase. Note following special circumstances
339 * taken from RFC 1459. Many "official" server branches still hold to this
340 * rule so i will too;
342 * Because of IRC's scandanavian origin, the characters {}| are
343 * considered to be the lower case equivalents of the characters []\,
344 * respectively. This is a critical issue when determining the
345 * equivalence of two nicknames.
347 void strlower(char *n)
351 for (char* t = n; *t; t++)
352 *t = lowermap[(unsigned char)*t];
356 /* Find a user record by nickname and return a pointer to it */
358 userrec* Find(const std::string &nick)
360 user_hash::iterator iter = clientlist.find(nick);
362 if (iter == clientlist.end())
363 /* Couldn't find it */
369 userrec* Find(const char* nick)
371 user_hash::iterator iter;
376 iter = clientlist.find(nick);
378 if (iter == clientlist.end())
384 /* find a channel record by channel name and return a pointer to it */
386 chanrec* FindChan(const char* chan)
388 chan_hash::iterator iter;
392 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
396 iter = chanlist.find(chan);
398 if (iter == chanlist.end())
399 /* Couldn't find it */
406 long GetMaxBans(char* name)
409 for (std::map<std::string,int>::iterator n = Config->maxbans.begin(); n != Config->maxbans.end(); n++)
412 if (match(name,x.c_str()))
420 void purge_empty_chans(userrec* u)
422 std::vector<chanrec*> to_delete;
424 // firstly decrement the count on each channel
425 for (std::vector<ucrec*>::iterator f = u->chans.begin(); f != u->chans.end(); f++)
427 ucrec* uc = (ucrec*)(*f);
430 if (uc->channel->DelUser(u) == 0)
432 /* No users left in here, mark it for deletion */
433 to_delete.push_back(uc->channel);
439 log(DEBUG,"purge_empty_chans: %d channels to delete",to_delete.size());
441 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
443 chanrec* thischan = (chanrec*)*n;
444 chan_hash::iterator i2 = chanlist.find(thischan->name);
445 if (i2 != chanlist.end())
447 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
457 char* chanmodes(chanrec *chan, bool showkey)
459 static char scratch[MAXBUF];
460 static char sparam[MAXBUF];
461 char* offset = scratch;
462 std::string extparam = "";
466 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
474 /* This was still iterating up to 190, chanrec::custom_modes is only 64 elements -- Om */
475 for(int n = 0; n < 64; n++)
484 extparam = (showkey ? chan->key : "<key>");
487 extparam = ConvToStr(chan->limit);
495 /* We know these have no parameters */
498 extparam = chan->GetModeParameter(n+65);
503 charlcat(sparam,' ',MAXBUF);
504 strlcat(sparam,extparam.c_str(),MAXBUF);
509 /* Null terminate scratch */
511 strlcat(scratch,sparam,MAXBUF);
516 /* compile a userlist of a channel into a string, each nick seperated by
517 * spaces and op, voice etc status shown as @ and + */
519 void userlist(userrec *user,chanrec *c)
523 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
530 dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
533 char* ptr = list + dlen;
535 CUList *ulist= c->GetUsers();
537 /* Improvement by Brain - this doesnt change in value, so why was it inside
540 bool has_user = c->HasUser(user);
542 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
544 if ((!has_user) && (i->second->modes[UM_INVISIBLE]))
547 * user is +i, and source not on the channel, does not show
553 size_t ptrlen = snprintf(ptr, MAXBUF, "%s%s ", cmode(i->second, c), i->second->nick);
560 if (curlen > (480-NICKMAX))
562 /* list overflowed into multiple numerics */
563 user->WriteServ(list);
565 /* reset our lengths */
566 dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
574 /* if whats left in the list isnt empty, send it */
577 user->WriteServ(list);
582 * return a count of the users on a specific channel accounting for
583 * invisible users who won't increase the count. e.g. for /LIST
585 int usercount_i(chanrec *c)
592 CUList *ulist= c->GetUsers();
593 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
595 if (!(i->second->modes[UM_INVISIBLE]))
602 int usercount(chanrec *c)
604 return (c ? c->GetUserCounter() : 0);
608 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
609 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
610 * then their ip will be taken as 'priority' anyway, so for example,
611 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
613 ConnectClass GetClass(userrec *user)
615 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
617 if ((match(user->GetIPString(),i->host.c_str(),true)) || (match(user->host,i->host.c_str())))
623 return *(Config->Classes.begin());
627 * sends out an error notice to all connected clients (not to be used
630 void send_error(char *s)
632 log(DEBUG,"send_error: %s",s);
634 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
636 userrec* t = (userrec*)(*i);
637 if (t->registered == REG_ALL)
639 t->WriteServ("NOTICE %s :%s",t->nick,s);
643 // fix - unregistered connections receive ERROR, not NOTICE
644 t->Write("ERROR :%s",s);
649 void Error(int status)
655 signal(SIGALRM, SIG_IGN);
656 signal(SIGPIPE, SIG_IGN);
657 signal(SIGTERM, SIG_IGN);
658 signal(SIGABRT, SIG_IGN);
659 signal(SIGSEGV, SIG_IGN);
660 signal(SIGURG, SIG_IGN);
661 signal(SIGKILL, SIG_IGN);
662 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
664 log(DEFAULT,"Please report the backtrace lines shown below with any bugreport to the bugtracker at http://www.inspircd.org/bugtrack/");
665 size = backtrace(array, 30);
666 strings = backtrace_symbols(array, size);
667 for (size_t i = 0; i < size; i++) {
668 log(DEFAULT,"[%d] %s", i, strings[i]);
671 WriteOpers("*** SIGSEGV: Please see the ircd.log for backtrace and report the error to http://www.inspircd.org/bugtrack/");
673 log(DEFAULT,"You do not have execinfo.h so i could not backtrace -- on FreeBSD, please install the libexecinfo port.");
675 send_error("Somebody screwed up... Whoops. IRC Server terminating.");
676 signal(SIGSEGV, SIG_DFL);
677 if (raise(SIGSEGV) == -1)
679 log(DEFAULT,"What the hell, i couldnt re-raise SIGSEGV! Error: %s",strerror(errno));
684 // this function counts all users connected, wether they are registered or NOT.
687 return clientlist.size();
690 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
691 int registered_usercount(void)
695 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
697 c += (i->second->registered == REG_ALL);
703 int usercount_invisible(void)
707 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
709 c += ((i->second->registered == REG_ALL) && (i->second->modes[UM_INVISIBLE]));
715 int usercount_opers(void)
719 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
721 if (*(i->second->oper))
727 int usercount_unknown(void)
731 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
733 userrec* t = (userrec*)(*i);
734 if (t->registered != REG_ALL)
743 return chanlist.size();
750 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
752 userrec* t = (userrec*)(*i);
753 if (t->registered == REG_ALL)
760 void ShowMOTD(userrec *user)
762 if (!Config->MOTD.size())
764 user->WriteServ("422 %s :Message of the day file is missing.",user->nick);
767 user->WriteServ("375 %s :%s message of the day", user->nick, Config->ServerName);
769 for (unsigned int i = 0; i < Config->MOTD.size(); i++)
770 user->WriteServ("372 %s :- %s",user->nick,Config->MOTD[i].c_str());
772 user->WriteServ("376 %s :End of message of the day.", user->nick);
775 void ShowRULES(userrec *user)
777 if (!Config->RULES.size())
779 user->WriteServ("NOTICE %s :Rules file is missing.",user->nick);
782 user->WriteServ("NOTICE %s :%s rules",user->nick,Config->ServerName);
784 for (unsigned int i = 0; i < Config->RULES.size(); i++)
785 user->WriteServ("NOTICE %s :%s",user->nick,Config->RULES[i].c_str());
787 user->WriteServ("NOTICE %s :End of %s rules.",user->nick,Config->ServerName);
790 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
791 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
792 // registration timeout maximum seconds)
793 bool AllModulesReportReady(userrec* user)
795 if (!Config->global_implementation[I_OnCheckReady])
798 for (int i = 0; i <= MODCOUNT; i++)
800 if (Config->implement_lists[i][I_OnCheckReady])
802 int res = modules[i]->OnCheckReady(user);
811 /* Make Sure Modules Are Avaliable!
812 * (BugFix By Craig.. See? I do work! :p)
813 * Modified by brain, requires const char*
814 * to work with other API functions
818 bool FileExists (const char* file)
821 if ((input = fopen (file, "r")) == NULL)
832 char* CleanFilename(char* name)
834 char* p = name + strlen(name);
835 while ((p != name) && (*p != '/')) p--;
836 return (p != name ? ++p : p);
839 bool DirValid(char* dirandfile)
843 char otherdir[MAXBUF];
846 strlcpy(work, dirandfile, MAXBUF);
849 // we just want the dir
861 // Get the current working directory
862 if (getcwd(buffer, MAXBUF ) == NULL )
867 if (getcwd(otherdir, MAXBUF ) == NULL )
872 size_t t = strlen(work);
874 if (strlen(otherdir) >= t)
878 if (!strcmp(otherdir,work))
891 std::string GetFullProgDir(char** argv, int argc)
895 char otherdir[MAXBUF];
898 strlcpy(work,argv[0],MAXBUF);
901 // we just want the dir
913 // Get the current working directory
914 if (getcwd(buffer, MAXBUF) == NULL)
919 if (getcwd(otherdir, MAXBUF) == NULL)
926 int InsertMode(std::string &output, const char* mode, unsigned short section)
928 unsigned short currsection = 1;
929 unsigned int pos = output.find("CHANMODES=", 0) + 10; // +10 for the length of "CHANMODES="
931 if(section > 4 || section == 0)
933 log(DEBUG, "InsertMode: CHANMODES doesn't have a section %dh :/", section);
937 for(; pos < output.size(); pos++)
939 if(section == currsection)
942 if(output[pos] == ',')
946 output.insert(pos, mode);
950 bool IsValidChannelName(const char *chname)
954 /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
955 if (!chname || *chname != '#')
960 c = (char *)chname + 1;
974 /* too long a name - note funky pointer arithmetic here. */
975 if ((c - chname) > CHANMAX)
983 inline int charlcat(char* x,char y,int z)
1000 bool charremove(char* mp, char remove)
1003 bool shift_down = false;
1007 if (*mptr == remove)
1019 void OpenLog(char** argv, int argc)
1023 if (Config->logpath == "")
1025 Config->logpath = GetFullProgDir(argv,argc) + "/ircd.log";
1030 Config->log_file = fopen(LOG_FILE,"a+");
1032 if (!Config->log_file)
1034 printf("ERROR: Could not write to logfile %s, bailing!\n\n",Config->logpath.c_str());
1041 Config->log_file = fopen(Config->logpath.c_str(),"a+");
1043 if (!Config->log_file)
1045 printf("ERROR: Could not write to logfile %s, bailing!\n\n",Config->logpath.c_str());
1054 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
1055 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
1062 if (*Config->DieValue)
1064 printf("WARNING: %s\n\n",Config->DieValue);
1065 log(DEFAULT,"Uh-Oh, somebody didn't read their config file: '%s'",Config->DieValue);
1070 /* We must load the modules AFTER initializing the socket engine, now */
1071 void LoadAllModules(InspIRCd* ServerInstance)
1073 char configToken[MAXBUF];
1074 Config->module_names.clear();
1077 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "module"); count++)
1079 Config->ConfValue(Config->config_data, "module","name",count,configToken,MAXBUF);
1080 printf("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
1082 if (!ServerInstance->LoadModule(configToken))
1084 log(DEFAULT,"Exiting due to a module loader error.");
1085 printf("\nThere was an error loading a module: %s\n\n",ServerInstance->ModuleError());
1090 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);