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());
110 std::string GetServerDescription(const char* servername)
112 std::string description = "";
114 FOREACH_MOD(I_OnGetServerDescription,OnGetServerDescription(servername,description));
116 if (description != "")
122 // not a remote server that can be found, it must be me.
123 return ServerInstance->Config->ServerDesc;
127 /* XXX - We don't use WriteMode for this because WriteMode is very slow and
128 * this isnt. Basically WriteMode has to iterate ALL the users 'n' times for
129 * the number of modes provided, e.g. if you send WriteMode 'og' to write to
130 * opers with globops, and you have 2000 users, thats 4000 iterations. WriteOpers
131 * uses the oper list, which means if you have 2000 users but only 5 opers,
132 * it iterates 5 times.
134 void WriteOpers(const char* text, ...)
136 char textbuffer[MAXBUF];
141 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
145 va_start(argsPtr, text);
146 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
149 WriteOpers_NoFormat(textbuffer);
152 void WriteOpers_NoFormat(const char* text)
156 log(DEFAULT,"*** BUG *** WriteOpers_NoFormat was given an invalid parameter");
160 for (std::vector<userrec*>::iterator i = all_opers.begin(); i != all_opers.end(); i++)
166 if (a->modes[UM_SERVERNOTICE])
168 // send server notices to all with +s
169 a->WriteServ("NOTICE %s :%s",a->nick,text);
175 void ServerNoticeAll(char* text, ...)
180 char textbuffer[MAXBUF];
181 char formatbuffer[MAXBUF];
183 va_start (argsPtr, text);
184 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
187 snprintf(formatbuffer,MAXBUF,"NOTICE $%s :%s",ServerInstance->Config->ServerName,textbuffer);
189 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
192 t->WriteServ(std::string(formatbuffer));
196 void ServerPrivmsgAll(char* text, ...)
201 char textbuffer[MAXBUF];
202 char formatbuffer[MAXBUF];
204 va_start (argsPtr, text);
205 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
208 snprintf(formatbuffer,MAXBUF,"PRIVMSG $%s :%s",ServerInstance->Config->ServerName,textbuffer);
210 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
213 t->WriteServ(std::string(formatbuffer));
217 void WriteMode(const char* modes, int flags, const char* text, ...)
219 char textbuffer[MAXBUF];
223 if ((!text) || (!modes) || (!flags))
225 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
229 va_start(argsPtr, text);
230 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
232 modelen = strlen(modes);
234 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
236 userrec* t = (userrec*)(*i);
237 bool send_to_user = false;
243 for (int n = 0; n < modelen; n++)
245 if (!t->modes[modes[n]-65])
247 send_to_user = false;
252 else if (flags == WM_OR)
254 send_to_user = false;
256 for (int n = 0; n < modelen; n++)
258 if (t->modes[modes[n]-65])
268 t->WriteServ("NOTICE %s :%s",t->nick,textbuffer);
273 void NoticeAll(userrec *source, bool local_only, char* text, ...)
275 char textbuffer[MAXBUF];
276 char formatbuffer[MAXBUF];
279 if ((!text) || (!source))
281 log(DEFAULT,"*** BUG *** NoticeAll was given an invalid parameter");
285 va_start(argsPtr, text);
286 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
289 snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
291 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
294 t->WriteFrom(source,std::string(formatbuffer));
299 /* convert a string to lowercase. Note following special circumstances
300 * taken from RFC 1459. Many "official" server branches still hold to this
301 * rule so i will too;
303 * Because of IRC's scandanavian origin, the characters {}| are
304 * considered to be the lower case equivalents of the characters []\,
305 * respectively. This is a critical issue when determining the
306 * equivalence of two nicknames.
308 void strlower(char *n)
312 for (char* t = n; *t; t++)
313 *t = lowermap[(unsigned char)*t];
317 /* Find a user record by nickname and return a pointer to it */
319 userrec* Find(const std::string &nick)
321 user_hash::iterator iter = clientlist.find(nick);
323 if (iter == clientlist.end())
324 /* Couldn't find it */
330 userrec* Find(const char* nick)
332 user_hash::iterator iter;
337 iter = clientlist.find(nick);
339 if (iter == clientlist.end())
345 /* find a channel record by channel name and return a pointer to it */
347 chanrec* FindChan(const char* chan)
349 chan_hash::iterator iter;
353 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
357 iter = chanlist.find(chan);
359 if (iter == chanlist.end())
360 /* Couldn't find it */
367 long GetMaxBans(char* name)
370 for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
373 if (match(name,x.c_str()))
381 void purge_empty_chans(userrec* u)
383 std::vector<chanrec*> to_delete;
385 // firstly decrement the count on each channel
386 for (std::vector<ucrec*>::iterator f = u->chans.begin(); f != u->chans.end(); f++)
388 ucrec* uc = (ucrec*)(*f);
391 if (uc->channel->DelUser(u) == 0)
393 /* No users left in here, mark it for deletion */
394 to_delete.push_back(uc->channel);
400 log(DEBUG,"purge_empty_chans: %d channels to delete",to_delete.size());
402 for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
404 chanrec* thischan = (chanrec*)*n;
405 chan_hash::iterator i2 = chanlist.find(thischan->name);
406 if (i2 != chanlist.end())
408 FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
418 char* chanmodes(chanrec *chan, bool showkey)
420 static char scratch[MAXBUF];
421 static char sparam[MAXBUF];
422 char* offset = scratch;
423 std::string extparam = "";
427 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
435 /* This was still iterating up to 190, chanrec::custom_modes is only 64 elements -- Om */
436 for(int n = 0; n < 64; n++)
445 extparam = (showkey ? chan->key : "<key>");
448 extparam = ConvToStr(chan->limit);
456 /* We know these have no parameters */
459 extparam = chan->GetModeParameter(n+65);
464 charlcat(sparam,' ',MAXBUF);
465 strlcat(sparam,extparam.c_str(),MAXBUF);
470 /* Null terminate scratch */
472 strlcat(scratch,sparam,MAXBUF);
477 /* compile a userlist of a channel into a string, each nick seperated by
478 * spaces and op, voice etc status shown as @ and + */
480 void userlist(userrec *user,chanrec *c)
484 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
491 dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
494 char* ptr = list + dlen;
496 CUList *ulist= c->GetUsers();
498 /* Improvement by Brain - this doesnt change in value, so why was it inside
501 bool has_user = c->HasUser(user);
503 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
505 if ((!has_user) && (i->second->modes[UM_INVISIBLE]))
508 * user is +i, and source not on the channel, does not show
514 size_t ptrlen = snprintf(ptr, MAXBUF, "%s%s ", cmode(i->second, c), i->second->nick);
521 if (curlen > (480-NICKMAX))
523 /* list overflowed into multiple numerics */
524 user->WriteServ(list);
526 /* reset our lengths */
527 dlen = curlen = snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
535 /* if whats left in the list isnt empty, send it */
538 user->WriteServ(list);
543 * return a count of the users on a specific channel accounting for
544 * invisible users who won't increase the count. e.g. for /LIST
546 int usercount_i(chanrec *c)
553 CUList *ulist= c->GetUsers();
554 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
556 if (!(i->second->modes[UM_INVISIBLE]))
563 int usercount(chanrec *c)
565 return (c ? c->GetUserCounter() : 0);
569 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
570 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
571 * then their ip will be taken as 'priority' anyway, so for example,
572 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
574 ConnectClass GetClass(userrec *user)
576 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
578 if ((match(user->GetIPString(),i->host.c_str(),true)) || (match(user->host,i->host.c_str())))
584 return *(ServerInstance->Config->Classes.begin());
588 * sends out an error notice to all connected clients (not to be used
591 void send_error(char *s)
593 log(DEBUG,"send_error: %s",s);
595 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
597 userrec* t = (userrec*)(*i);
598 if (t->registered == REG_ALL)
600 t->WriteServ("NOTICE %s :%s",t->nick,s);
604 // fix - unregistered connections receive ERROR, not NOTICE
605 t->Write("ERROR :%s",s);
610 void Error(int status)
616 signal(SIGALRM, SIG_IGN);
617 signal(SIGPIPE, SIG_IGN);
618 signal(SIGTERM, SIG_IGN);
619 signal(SIGABRT, SIG_IGN);
620 signal(SIGSEGV, SIG_IGN);
621 signal(SIGURG, SIG_IGN);
622 signal(SIGKILL, SIG_IGN);
623 log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
625 log(DEFAULT,"Please report the backtrace lines shown below with any bugreport to the bugtracker at http://www.inspircd.org/bugtrack/");
626 size = backtrace(array, 30);
627 strings = backtrace_symbols(array, size);
628 for (size_t i = 0; i < size; i++) {
629 log(DEFAULT,"[%d] %s", i, strings[i]);
632 WriteOpers("*** SIGSEGV: Please see the ircd.log for backtrace and report the error to http://www.inspircd.org/bugtrack/");
634 log(DEFAULT,"You do not have execinfo.h so i could not backtrace -- on FreeBSD, please install the libexecinfo port.");
636 send_error("Somebody screwed up... Whoops. IRC Server terminating.");
637 signal(SIGSEGV, SIG_DFL);
638 if (raise(SIGSEGV) == -1)
640 log(DEFAULT,"What the hell, i couldnt re-raise SIGSEGV! Error: %s",strerror(errno));
645 // this function counts all users connected, wether they are registered or NOT.
648 return clientlist.size();
651 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
652 int registered_usercount(void)
656 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
658 c += (i->second->registered == REG_ALL);
664 int usercount_invisible(void)
668 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
670 c += ((i->second->registered == REG_ALL) && (i->second->modes[UM_INVISIBLE]));
676 int usercount_opers(void)
680 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
682 if (*(i->second->oper))
688 int usercount_unknown(void)
692 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
694 userrec* t = (userrec*)(*i);
695 if (t->registered != REG_ALL)
704 return chanlist.size();
711 for (std::vector<userrec*>::const_iterator i = local_users.begin(); i != local_users.end(); i++)
713 userrec* t = (userrec*)(*i);
714 if (t->registered == REG_ALL)
721 void ShowMOTD(userrec *user)
723 if (!ServerInstance->Config->MOTD.size())
725 user->WriteServ("422 %s :Message of the day file is missing.",user->nick);
728 user->WriteServ("375 %s :%s message of the day", user->nick, ServerInstance->Config->ServerName);
730 for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
731 user->WriteServ("372 %s :- %s",user->nick,ServerInstance->Config->MOTD[i].c_str());
733 user->WriteServ("376 %s :End of message of the day.", user->nick);
736 void ShowRULES(userrec *user)
738 if (!ServerInstance->Config->RULES.size())
740 user->WriteServ("NOTICE %s :Rules file is missing.",user->nick);
743 user->WriteServ("NOTICE %s :%s rules",user->nick,ServerInstance->Config->ServerName);
745 for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
746 user->WriteServ("NOTICE %s :%s",user->nick,ServerInstance->Config->RULES[i].c_str());
748 user->WriteServ("NOTICE %s :End of %s rules.",user->nick,ServerInstance->Config->ServerName);
751 // this returns 1 when all modules are satisfied that the user should be allowed onto the irc server
752 // (until this returns true, a user will block in the waiting state, waiting to connect up to the
753 // registration timeout maximum seconds)
754 bool AllModulesReportReady(userrec* user)
756 if (!ServerInstance->Config->global_implementation[I_OnCheckReady])
759 for (int i = 0; i <= MODCOUNT; i++)
761 if (ServerInstance->Config->implement_lists[i][I_OnCheckReady])
763 int res = modules[i]->OnCheckReady(user);
772 /* Make Sure Modules Are Avaliable!
773 * (BugFix By Craig.. See? I do work! :p)
774 * Modified by brain, requires const char*
775 * to work with other API functions
779 bool FileExists (const char* file)
782 if ((input = fopen (file, "r")) == NULL)
793 char* CleanFilename(char* name)
795 char* p = name + strlen(name);
796 while ((p != name) && (*p != '/')) p--;
797 return (p != name ? ++p : p);
800 bool DirValid(char* dirandfile)
804 char otherdir[MAXBUF];
807 strlcpy(work, dirandfile, MAXBUF);
810 // we just want the dir
822 // Get the current working directory
823 if (getcwd(buffer, MAXBUF ) == NULL )
828 if (getcwd(otherdir, MAXBUF ) == NULL )
833 size_t t = strlen(work);
835 if (strlen(otherdir) >= t)
839 if (!strcmp(otherdir,work))
852 std::string GetFullProgDir(char** argv, int argc)
856 char otherdir[MAXBUF];
859 strlcpy(work,argv[0],MAXBUF);
862 // we just want the dir
874 // Get the current working directory
875 if (getcwd(buffer, MAXBUF) == NULL)
880 if (getcwd(otherdir, MAXBUF) == NULL)
887 int InsertMode(std::string &output, const char* mode, unsigned short section)
889 unsigned short currsection = 1;
890 unsigned int pos = output.find("CHANMODES=", 0) + 10; // +10 for the length of "CHANMODES="
892 if(section > 4 || section == 0)
894 log(DEBUG, "InsertMode: CHANMODES doesn't have a section %dh :/", section);
898 for(; pos < output.size(); pos++)
900 if(section == currsection)
903 if(output[pos] == ',')
907 output.insert(pos, mode);
911 bool IsValidChannelName(const char *chname)
915 /* check for no name - don't check for !*chname, as if it is empty, it won't be '#'! */
916 if (!chname || *chname != '#')
921 c = (char *)chname + 1;
935 /* too long a name - note funky pointer arithmetic here. */
936 if ((c - chname) > CHANMAX)
944 inline int charlcat(char* x,char y,int z)
961 bool charremove(char* mp, char remove)
964 bool shift_down = false;
980 void OpenLog(char** argv, int argc)
984 if (ServerInstance->Config->logpath == "")
986 ServerInstance->Config->logpath = GetFullProgDir(argv,argc) + "/ircd.log";
991 ServerInstance->Config->log_file = fopen(LOG_FILE,"a+");
993 if (!ServerInstance->Config->log_file)
995 printf("ERROR: Could not write to logfile %s, bailing!\n\n",ServerInstance->Config->logpath.c_str());
1002 ServerInstance->Config->log_file = fopen(ServerInstance->Config->logpath.c_str(),"a+");
1004 if (!ServerInstance->Config->log_file)
1006 printf("ERROR: Could not write to logfile %s, bailing!\n\n",ServerInstance->Config->logpath.c_str());
1015 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
1016 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
1023 if (*ServerInstance->Config->DieValue)
1025 printf("WARNING: %s\n\n",ServerInstance->Config->DieValue);
1026 log(DEFAULT,"Uh-Oh, somebody didn't read their config file: '%s'",ServerInstance->Config->DieValue);
1031 /* We must load the modules AFTER initializing the socket engine, now */
1032 void LoadAllModules(InspIRCd* ServerInstance)
1034 char configToken[MAXBUF];
1035 ServerInstance->Config->module_names.clear();
1038 for (int count = 0; count < ServerInstance->Config->ConfValueEnum(ServerInstance->Config->config_data, "module"); count++)
1040 ServerInstance->Config->ConfValue(ServerInstance->Config->config_data, "module","name",count,configToken,MAXBUF);
1041 printf("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
1043 if (!ServerInstance->LoadModule(configToken))
1045 log(DEFAULT,"Exiting due to a module loader error.");
1046 printf("\nThere was an error loading a module: %s\n\n",ServerInstance->ModuleError());
1051 log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);