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 * ---------------------------------------------------
19 #include "inspircd_config.h"
21 #include "inspircd_io.h"
22 #include "inspircd_util.h"
24 #include <sys/errno.h>
27 #include <sys/types.h>
28 #include <sys/event.h>
33 #include <sys/epoll.h>
39 #include <ext/hash_map>
47 #include "connection.h"
59 #include "inspstring.h"
60 #include "helperfuncs.h"
73 extern std::vector<Module*> modules;
74 extern std::vector<ircd_module*> factory;
76 extern std::vector<std::string> include_stack;
78 extern std::vector<InspSocket*> module_sockets;
83 extern char ServerName[MAXBUF];
84 extern char Network[MAXBUF];
85 extern char ServerDesc[MAXBUF];
86 extern char AdminName[MAXBUF];
87 extern char AdminEmail[MAXBUF];
88 extern char AdminNick[MAXBUF];
89 extern char diepass[MAXBUF];
90 extern char restartpass[MAXBUF];
91 extern char motd[MAXBUF];
92 extern char rules[MAXBUF];
93 extern char list[MAXBUF];
94 extern char PrefixQuit[MAXBUF];
95 extern char DieValue[MAXBUF];
98 extern int WHOWAS_STALE;
99 extern int WHOWAS_MAX;
101 extern time_t startup_time;
102 extern int NetBufferSize;
103 extern int MaxWhoResults;
104 extern time_t nb_start;
106 extern std::vector<std::string> module_names;
108 extern int boundPortCount;
109 extern int portCount;
110 extern int SERVERportCount;
111 extern int ports[MAXSOCKS];
112 extern int defaultRoute;
114 extern std::vector<long> auth_cookies;
115 extern std::stringstream config_f;
117 extern serverrec* me[32];
119 extern FILE *log_file;
121 extern userrec* fd_ref_table[65536];
123 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
124 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
125 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
126 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
127 typedef std::deque<command_t> command_table;
130 extern user_hash clientlist;
131 extern chan_hash chanlist;
132 extern whowas_hash whowas;
133 extern command_table cmdlist;
134 extern file_cache MOTD;
135 extern file_cache RULES;
136 extern address_cache IP;
139 // class type for holding an extended mode character - internal to core
141 class ExtMode : public classbase
150 ExtMode(char mc, int ty, bool oper, int p_on, int p_off) : modechar(mc), type(ty), needsoper(oper), params_when_on(p_on), params_when_off(p_off) { };
153 typedef std::vector<ExtMode> ExtModeList;
154 typedef ExtModeList::iterator ExtModeListIter;
159 // returns true if an extended mode character is in use
160 bool ModeDefined(char modechar, int type)
162 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
164 if ((i->modechar == modechar) && (i->type == type))
172 bool ModeIsListMode(char modechar, int type)
174 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
176 if ((i->modechar == modechar) && (i->type == type) && (i->list == true))
184 bool ModeDefinedOper(char modechar, int type)
186 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
188 if ((i->modechar == modechar) && (i->type == type) && (i->needsoper == true))
196 // returns number of parameters for a custom mode when it is switched on
197 int ModeDefinedOn(char modechar, int type)
199 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
201 if ((i->modechar == modechar) && (i->type == type))
203 return i->params_when_on;
209 // returns number of parameters for a custom mode when it is switched on
210 int ModeDefinedOff(char modechar, int type)
212 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
214 if ((i->modechar == modechar) && (i->type == type))
216 return i->params_when_off;
222 // returns true if an extended mode character is in use
223 bool DoAddExtendedMode(char modechar, int type, bool requires_oper, int params_on, int params_off)
225 if (ModeDefined(modechar,type)) {
228 EMode.push_back(ExtMode(modechar,type,requires_oper,params_on,params_off));
232 // turns a mode into a listmode
233 void ModeMakeList(char modechar)
235 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
237 if ((i->modechar == modechar) && (i->type == MT_CHANNEL))
246 // version is a simple class for holding a modules version number
248 Version::Version(int major, int minor, int revision, int build, int flags) : Major(major), Minor(minor), Revision(revision), Build(build), Flags(flags) { };
250 // admin is a simple class for holding a server's administrative info
252 Admin::Admin(std::string name, std::string email, std::string nick) : Name(name), Email(email), Nick(nick) { };
254 Request::Request(char* anydata, Module* src, Module* dst) : data(anydata), source(src), dest(dst) { };
256 char* Request::GetData()
261 Module* Request::GetSource()
266 Module* Request::GetDest()
271 char* Request::Send()
275 return dest->OnRequest(this);
283 Event::Event(char* anydata, Module* src, std::string eventid) : data(anydata), source(src), id(eventid) { };
285 char* Event::GetData()
290 Module* Event::GetSource()
297 FOREACH_MOD OnEvent(this);
301 std::string Event::GetEventID()
307 // These declarations define the behavours of the base class Module (which does nothing at all)
309 Module::~Module() { }
310 void Module::OnUserConnect(userrec* user) { }
311 void Module::OnUserQuit(userrec* user) { }
312 void Module::OnUserDisconnect(userrec* user) { }
313 void Module::OnUserJoin(userrec* user, chanrec* channel) { }
314 void Module::OnUserPart(userrec* user, chanrec* channel) { }
315 void Module::OnPacketTransmit(std::string &data, std::string serv) { }
316 void Module::OnPacketReceive(std::string &data, std::string serv) { }
317 void Module::OnRehash() { }
318 void Module::OnServerRaw(std::string &raw, bool inbound, userrec* user) { }
319 int Module::OnUserPreJoin(userrec* user, chanrec* chan, const char* cname) { return 0; }
320 int Module::OnExtendedMode(userrec* user, void* target, char modechar, int type, bool mode_on, string_list ¶ms) { return false; }
321 Version Module::GetVersion() { return Version(1,0,0,0,VF_VENDOR); }
322 void Module::OnOper(userrec* user) { };
323 void Module::OnInfo(userrec* user) { };
324 void Module::OnWhois(userrec* source, userrec* dest) { };
325 int Module::OnUserPreInvite(userrec* source,userrec* dest,chanrec* channel) { return 0; };
326 int Module::OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text) { return 0; };
327 int Module::OnUserPreNotice(userrec* user,void* dest,int target_type, std::string &text) { return 0; };
328 int Module::OnUserPreNick(userrec* user, std::string newnick) { return 0; };
329 void Module::OnUserPostNick(userrec* user, std::string oldnick) { };
330 int Module::OnAccessCheck(userrec* source,userrec* dest,chanrec* channel,int access_type) { return ACR_DEFAULT; };
331 string_list Module::OnUserSync(userrec* user) { string_list empty; return empty; }
332 string_list Module::OnChannelSync(chanrec* chan) { string_list empty; return empty; }
333 void Module::On005Numeric(std::string &output) { };
334 int Module::OnKill(userrec* source, userrec* dest, std::string reason) { return 0; };
335 void Module::OnLoadModule(Module* mod,std::string name) { };
336 void Module::OnUnloadModule(Module* mod,std::string name) { };
337 void Module::OnBackgroundTimer(time_t curtime) { };
338 void Module::OnSendList(userrec* user, chanrec* channel, char mode) { };
339 int Module::OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user) { return 0; };
340 bool Module::OnCheckReady(userrec* user) { return true; };
341 void Module::OnUserRegister(userrec* user) { };
342 int Module::OnUserPreKick(userrec* source, userrec* user, chanrec* chan, std::string reason) { return 0; };
343 void Module::OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason) { };
344 int Module::OnRawMode(userrec* user, chanrec* chan, char mode, std::string param, bool adding, int pcnt) { return 0; };
345 int Module::OnCheckInvite(userrec* user, chanrec* chan) { return 0; };
346 int Module::OnCheckKey(userrec* user, chanrec* chan, std::string keygiven) { return 0; };
347 int Module::OnCheckLimit(userrec* user, chanrec* chan) { return 0; };
348 int Module::OnCheckBan(userrec* user, chanrec* chan) { return 0; };
349 void Module::OnStats(char symbol) { };
350 int Module::OnChangeLocalUserHost(userrec* user, std::string newhost) { return 0; };
351 int Module::OnChangeLocalUserGECOS(userrec* user, std::string newhost) { return 0; };
352 int Module::OnLocalTopicChange(userrec* user, chanrec* chan, std::string topic) { return 0; };
353 void Module::OnEvent(Event* event) { return; };
354 char* Module::OnRequest(Request* request) { return NULL; };
355 int Module::OnOperCompare(std::string password, std::string input) { return 0; };
356 void Module::OnGlobalOper(userrec* user) { };
357 void Module::OnGlobalConnect(userrec* user) { };
358 int Module::OnAddBan(userrec* source, chanrec* channel,std::string banmask) { return 0; };
359 int Module::OnDelBan(userrec* source, chanrec* channel,std::string banmask) { return 0; };
360 void Module::OnRawSocketAccept(int fd, std::string ip, int localport) { };
361 int Module::OnRawSocketWrite(int fd, char* buffer, int count) { return 0; };
362 void Module::OnRawSocketClose(int fd) { };
363 int Module::OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { return 0; };
365 // server is a wrapper class that provides methods to all of the C-style
366 // exports in the core
377 void Server::AddSocket(InspSocket* sock)
379 module_sockets.push_back(sock);
382 void Server::SendOpers(std::string s)
384 WriteOpers("%s",s.c_str());
387 bool Server::MatchText(std::string sliteral, std::string spattern)
389 char literal[MAXBUF],pattern[MAXBUF];
390 strlcpy(literal,sliteral.c_str(),MAXBUF);
391 strlcpy(pattern,spattern.c_str(),MAXBUF);
392 return match(literal,pattern);
395 void Server::SendToModeMask(std::string modes, int flags, std::string text)
397 WriteMode(modes.c_str(),flags,"%s",text.c_str());
400 chanrec* Server::JoinUserToChannel(userrec* user, std::string cname, std::string key)
402 return add_channel(user,cname.c_str(),key.c_str(),false);
405 chanrec* Server::PartUserFromChannel(userrec* user, std::string cname, std::string reason)
407 return del_channel(user,cname.c_str(),reason.c_str(),false);
410 chanuserlist Server::GetUsers(chanrec* chan)
414 std::vector<char*> *list = chan->GetUsers();
415 for (std::vector<char*>::iterator i = list->begin(); i != list->end(); i++)
418 userl.push_back((userrec*)o);
422 void Server::ChangeUserNick(userrec* user, std::string nickname)
424 force_nickchange(user,nickname.c_str());
427 void Server::QuitUser(userrec* user, std::string reason)
429 kill_link(user,reason.c_str());
432 bool Server::IsUlined(std::string server)
434 return is_uline(server.c_str());
437 void Server::CallCommandHandler(std::string commandname, char** parameters, int pcnt, userrec* user)
439 call_handler(commandname.c_str(),parameters,pcnt,user);
442 void Server::Log(int level, std::string s)
444 log(level,"%s",s.c_str());
447 void Server::AddCommand(char* cmd, handlerfunc f, char flags, int minparams, char* source)
449 createcommand(cmd,f,flags,minparams,source);
452 void Server::SendMode(char **parameters, int pcnt, userrec *user)
454 server_mode(parameters,pcnt,user);
457 void Server::Send(int Socket, std::string s)
459 Write(Socket,"%s",s.c_str());
462 void Server::SendServ(int Socket, std::string s)
464 WriteServ(Socket,"%s",s.c_str());
467 void Server::SendFrom(int Socket, userrec* User, std::string s)
469 WriteFrom(Socket,User,"%s",s.c_str());
472 void Server::SendTo(userrec* Source, userrec* Dest, std::string s)
476 // if source is NULL, then the message originates from the local server
477 Write(Dest->fd,":%s %s",this->GetServerName().c_str(),s.c_str());
481 // otherwise it comes from the user specified
482 WriteTo(Source,Dest,"%s",s.c_str());
486 void Server::SendChannelServerNotice(std::string ServName, chanrec* Channel, std::string text)
488 WriteChannelWithServ((char*)ServName.c_str(), Channel, "%s", text.c_str());
491 void Server::SendChannel(userrec* User, chanrec* Channel, std::string s,bool IncludeSender)
495 WriteChannel(Channel,User,"%s",s.c_str());
499 ChanExceptSender(Channel,User,"%s",s.c_str());
503 bool Server::CommonChannels(userrec* u1, userrec* u2)
505 return (common_channels(u1,u2) != 0);
508 void Server::SendCommon(userrec* User, std::string text,bool IncludeSender)
512 WriteCommon(User,"%s",text.c_str());
516 WriteCommonExcept(User,"%s",text.c_str());
520 void Server::SendWallops(userrec* User, std::string text)
522 WriteWallOps(User,false,"%s",text.c_str());
525 void Server::ChangeHost(userrec* user, std::string host)
527 ChangeDisplayedHost(user,host.c_str());
530 void Server::ChangeGECOS(userrec* user, std::string gecos)
532 ChangeName(user,gecos.c_str());
535 bool Server::IsNick(std::string nick)
537 return (isnick(nick.c_str()) != 0);
540 userrec* Server::FindNick(std::string nick)
545 userrec* Server::FindDescriptor(int socket)
547 return (socket < 65536 ? fd_ref_table[socket] : NULL);
550 chanrec* Server::FindChannel(std::string channel)
552 return FindChan(channel.c_str());
555 std::string Server::ChanMode(userrec* User, chanrec* Chan)
557 return cmode(User,Chan);
560 bool Server::IsOnChannel(userrec* User, chanrec* Chan)
562 return has_channel(User,Chan);
565 std::string Server::GetServerName()
567 return getservername();
570 std::string Server::GetNetworkName()
572 return getnetworkname();
575 std::string Server::GetServerDescription()
577 return getserverdesc();
580 Admin Server::GetAdmin()
582 return Admin(getadminname(),getadminemail(),getadminnick());
587 bool Server::AddExtendedMode(char modechar, int type, bool requires_oper, int params_when_on, int params_when_off)
589 if (((modechar >= 'A') && (modechar <= 'Z')) || ((modechar >= 'a') && (modechar <= 'z')))
591 if (type == MT_SERVER)
593 log(DEBUG,"*** API ERROR *** Modes of type MT_SERVER are reserved for future expansion");
596 if (((params_when_on>0) || (params_when_off>0)) && (type == MT_CLIENT))
598 log(DEBUG,"*** API ERROR *** Parameters on MT_CLIENT modes are not supported");
601 if ((params_when_on>1) || (params_when_off>1))
603 log(DEBUG,"*** API ERROR *** More than one parameter for an MT_CHANNEL mode is not yet supported");
606 return DoAddExtendedMode(modechar,type,requires_oper,params_when_on,params_when_off);
610 log(DEBUG,"*** API ERROR *** Muppet modechar detected.");
615 bool Server::AddExtendedListMode(char modechar)
617 bool res = DoAddExtendedMode(modechar,MT_CHANNEL,false,1,1);
619 ModeMakeList(modechar);
623 int Server::CountUsers(chanrec* c)
629 bool Server::UserToPseudo(userrec* user,std::string message)
631 unsigned int old_fd = user->fd;
632 user->fd = FD_MAGIC_NUMBER;
634 Write(old_fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,message.c_str());
637 EV_SET(&ke, old_fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
638 int i = kevent(kq, &ke, 1, 0, 0, NULL);
641 log(DEBUG,"kqueue: Failed to remove user from queue!");
645 struct epoll_event ev;
646 ev.events = EPOLLIN | EPOLLET;
648 int i = epoll_ctl(ep, EPOLL_CTL_DEL, old_fd, &ev);
651 log(DEBUG,"epoll: List deletion failure!");
660 bool Server::PseudoToUser(userrec* alive,userrec* zombie,std::string message)
662 zombie->fd = alive->fd;
663 alive->fd = FD_MAGIC_NUMBER;
664 alive->ClearBuffer();
665 Write(zombie->fd,":%s!%s@%s NICK %s",alive->nick,alive->ident,alive->host,zombie->nick);
666 kill_link(alive,message.c_str());
667 fd_ref_table[zombie->fd] = zombie;
668 for (int i = 0; i != MAXCHANS; i++)
670 if (zombie->chans[i].channel != NULL)
672 if (zombie->chans[i].channel->name)
674 chanrec* Ptr = zombie->chans[i].channel;
675 WriteFrom(zombie->fd,zombie,"JOIN %s",Ptr->name);
678 WriteServ(zombie->fd,"332 %s %s :%s", zombie->nick, Ptr->name, Ptr->topic);
679 WriteServ(zombie->fd,"333 %s %s %s %d", zombie->nick, Ptr->name, Ptr->setby, Ptr->topicset);
681 userlist(zombie,Ptr);
682 WriteServ(zombie->fd,"366 %s %s :End of /NAMES list.", zombie->nick, Ptr->name);
690 void Server::AddGLine(long duration, std::string source, std::string reason, std::string hostmask)
692 add_gline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
695 void Server::AddQLine(long duration, std::string source, std::string reason, std::string nickname)
697 add_qline(duration, source.c_str(), reason.c_str(), nickname.c_str());
700 void Server::AddZLine(long duration, std::string source, std::string reason, std::string ipaddr)
702 add_zline(duration, source.c_str(), reason.c_str(), ipaddr.c_str());
705 void Server::AddKLine(long duration, std::string source, std::string reason, std::string hostmask)
707 add_kline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
710 void Server::AddELine(long duration, std::string source, std::string reason, std::string hostmask)
712 add_eline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
715 bool Server::DelGLine(std::string hostmask)
717 return del_gline(hostmask.c_str());
720 bool Server::DelQLine(std::string nickname)
722 return del_qline(nickname.c_str());
725 bool Server::DelZLine(std::string ipaddr)
727 return del_zline(ipaddr.c_str());
730 bool Server::DelKLine(std::string hostmask)
732 return del_kline(hostmask.c_str());
735 bool Server::DelELine(std::string hostmask)
737 return del_eline(hostmask.c_str());
740 long Server::CalcDuration(std::string delta)
742 return duration(delta.c_str());
745 bool Server::IsValidMask(std::string mask)
747 const char* dest = mask.c_str();
748 if (strchr(dest,'!')==0)
750 if (strchr(dest,'@')==0)
752 for (unsigned int i = 0; i < strlen(dest); i++)
755 for (unsigned int i = 0; i < strlen(dest); i++)
759 for (unsigned int i = 0; i < strlen(dest); i++)
765 for (unsigned int i = 0; i < strlen(dest); i++)
774 Module* Server::FindModule(std::string name)
776 for (int i = 0; i <= MODCOUNT; i++)
778 if (module_names[i] == name)
786 ConfigReader::ConfigReader()
788 include_stack.clear();
789 this->cache = new std::stringstream(std::stringstream::in | std::stringstream::out);
790 this->errorlog = new std::stringstream(std::stringstream::in | std::stringstream::out);
791 this->readerror = LoadConf(CONFIG_FILE,this->cache,this->errorlog);
792 if (!this->readerror)
793 this->error = CONF_FILE_NOT_FOUND;
797 ConfigReader::~ConfigReader()
802 delete this->errorlog;
806 ConfigReader::ConfigReader(std::string filename)
808 this->cache = new std::stringstream(std::stringstream::in | std::stringstream::out);
809 this->errorlog = new std::stringstream(std::stringstream::in | std::stringstream::out);
810 this->readerror = LoadConf(filename.c_str(),this->cache,this->errorlog);
811 if (!this->readerror)
812 this->error = CONF_FILE_NOT_FOUND;
815 std::string ConfigReader::ReadValue(std::string tag, std::string name, int index)
820 strlcpy(t,tag.c_str(),MAXBUF);
821 strlcpy(n,name.c_str(),MAXBUF);
822 int res = ReadConf(cache,t,n,index,val);
825 this->error = CONF_VALUE_NOT_FOUND;
831 bool ConfigReader::ReadFlag(std::string tag, std::string name, int index)
836 strlcpy(t,tag.c_str(),MAXBUF);
837 strlcpy(n,name.c_str(),MAXBUF);
838 int res = ReadConf(cache,t,n,index,val);
841 this->error = CONF_VALUE_NOT_FOUND;
845 return ((s == "yes") || (s == "YES") || (s == "true") || (s == "TRUE") || (s == "1"));
848 long ConfigReader::ReadInteger(std::string tag, std::string name, int index, bool needs_unsigned)
853 strlcpy(t,tag.c_str(),MAXBUF);
854 strlcpy(n,name.c_str(),MAXBUF);
855 int res = ReadConf(cache,t,n,index,val);
858 this->error = CONF_VALUE_NOT_FOUND;
861 for (unsigned int i = 0; i < strlen(val); i++)
863 if (!isdigit(val[i]))
865 this->error = CONF_NOT_A_NUMBER;
869 if ((needs_unsigned) && (atoi(val)<0))
871 this->error = CONF_NOT_UNSIGNED;
877 long ConfigReader::GetError()
879 long olderr = this->error;
884 void ConfigReader::DumpErrors(bool bail, userrec* user)
888 printf("There were errors in your configuration:\n%s",errorlog->str().c_str());
896 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
897 while (!errorlog->eof())
899 errorlog->getline(dataline,1024);
900 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
905 WriteOpers("There were errors in the configuration file:",user->nick);
906 while (!errorlog->eof())
908 errorlog->getline(dataline,1024);
909 WriteOpers(dataline);
917 int ConfigReader::Enumerate(std::string tag)
919 return EnumConf(cache,tag.c_str());
922 int ConfigReader::EnumerateValues(std::string tag, int index)
924 return EnumValues(cache, tag.c_str(), index);
927 bool ConfigReader::Verify()
929 return this->readerror;
933 FileReader::FileReader(std::string filename)
936 readfile(c,filename.c_str());
940 FileReader::FileReader()
944 void FileReader::LoadFile(std::string filename)
947 readfile(c,filename.c_str());
952 FileReader::~FileReader()
956 bool FileReader::Exists()
968 std::string FileReader::GetLine(int x)
970 if ((x<0) || ((unsigned)x>fc.size()))
975 int FileReader::FileSize()
981 std::vector<Module*> modules(255);
982 std::vector<ircd_module*> factory(255);