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 * ---------------------------------------------------
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.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"
72 extern std::vector<Module*> modules;
73 extern std::vector<ircd_module*> factory;
78 extern char ServerName[MAXBUF];
79 extern char Network[MAXBUF];
80 extern char ServerDesc[MAXBUF];
81 extern char AdminName[MAXBUF];
82 extern char AdminEmail[MAXBUF];
83 extern char AdminNick[MAXBUF];
84 extern char diepass[MAXBUF];
85 extern char restartpass[MAXBUF];
86 extern char motd[MAXBUF];
87 extern char rules[MAXBUF];
88 extern char list[MAXBUF];
89 extern char PrefixQuit[MAXBUF];
90 extern char DieValue[MAXBUF];
93 extern int WHOWAS_STALE;
94 extern int WHOWAS_MAX;
96 extern time_t startup_time;
97 extern int NetBufferSize;
98 extern int MaxWhoResults;
99 extern time_t nb_start;
101 extern std::vector<std::string> module_names;
103 extern int boundPortCount;
104 extern int portCount;
105 extern int SERVERportCount;
106 extern int ports[MAXSOCKS];
107 extern int defaultRoute;
109 extern std::vector<long> auth_cookies;
110 extern std::stringstream config_f;
112 extern serverrec* me[32];
114 extern FILE *log_file;
116 extern userrec* fd_ref_table[65536];
118 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
119 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
120 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
121 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
122 typedef std::deque<command_t> command_table;
125 extern user_hash clientlist;
126 extern chan_hash chanlist;
127 extern whowas_hash whowas;
128 extern command_table cmdlist;
129 extern file_cache MOTD;
130 extern file_cache RULES;
131 extern address_cache IP;
134 // class type for holding an extended mode character - internal to core
136 class ExtMode : public classbase
145 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) { };
148 typedef std::vector<ExtMode> ExtModeList;
149 typedef ExtModeList::iterator ExtModeListIter;
154 // returns true if an extended mode character is in use
155 bool ModeDefined(char modechar, int type)
157 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
159 if ((i->modechar == modechar) && (i->type == type))
167 bool ModeIsListMode(char modechar, int type)
169 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
171 if ((i->modechar == modechar) && (i->type == type) && (i->list == true))
179 bool ModeDefinedOper(char modechar, int type)
181 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
183 if ((i->modechar == modechar) && (i->type == type) && (i->needsoper == true))
191 // returns number of parameters for a custom mode when it is switched on
192 int ModeDefinedOn(char modechar, int type)
194 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
196 if ((i->modechar == modechar) && (i->type == type))
198 return i->params_when_on;
204 // returns number of parameters for a custom mode when it is switched on
205 int ModeDefinedOff(char modechar, int type)
207 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
209 if ((i->modechar == modechar) && (i->type == type))
211 return i->params_when_off;
217 // returns true if an extended mode character is in use
218 bool DoAddExtendedMode(char modechar, int type, bool requires_oper, int params_on, int params_off)
220 if (ModeDefined(modechar,type)) {
223 EMode.push_back(ExtMode(modechar,type,requires_oper,params_on,params_off));
227 // turns a mode into a listmode
228 void ModeMakeList(char modechar)
230 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
232 if ((i->modechar == modechar) && (i->type == MT_CHANNEL))
241 // version is a simple class for holding a modules version number
243 Version::Version(int major, int minor, int revision, int build, int flags) : Major(major), Minor(minor), Revision(revision), Build(build), Flags(flags) { };
245 // admin is a simple class for holding a server's administrative info
247 Admin::Admin(std::string name, std::string email, std::string nick) : Name(name), Email(email), Nick(nick) { };
249 Request::Request(char* anydata, Module* src, Module* dst) : data(anydata), source(src), dest(dst) { };
251 char* Request::GetData()
256 Module* Request::GetSource()
261 Module* Request::GetDest()
266 char* Request::Send()
270 return dest->OnRequest(this);
278 Event::Event(char* anydata, Module* src, std::string eventid) : data(anydata), source(src), id(eventid) { };
280 char* Event::GetData()
285 Module* Event::GetSource()
292 FOREACH_MOD OnEvent(this);
296 std::string Event::GetEventID()
302 // These declarations define the behavours of the base class Module (which does nothing at all)
304 Module::~Module() { }
305 void Module::OnUserConnect(userrec* user) { }
306 void Module::OnUserQuit(userrec* user) { }
307 void Module::OnUserDisconnect(userrec* user) { }
308 void Module::OnUserJoin(userrec* user, chanrec* channel) { }
309 void Module::OnUserPart(userrec* user, chanrec* channel) { }
310 void Module::OnPacketTransmit(std::string &data, std::string serv) { }
311 void Module::OnPacketReceive(std::string &data, std::string serv) { }
312 void Module::OnRehash() { }
313 void Module::OnServerRaw(std::string &raw, bool inbound, userrec* user) { }
314 int Module::OnUserPreJoin(userrec* user, chanrec* chan, const char* cname) { return 0; }
315 int Module::OnExtendedMode(userrec* user, void* target, char modechar, int type, bool mode_on, string_list ¶ms) { return false; }
316 Version Module::GetVersion() { return Version(1,0,0,0,VF_VENDOR); }
317 void Module::OnOper(userrec* user) { };
318 void Module::OnInfo(userrec* user) { };
319 void Module::OnWhois(userrec* source, userrec* dest) { };
320 int Module::OnUserPreInvite(userrec* source,userrec* dest,chanrec* channel) { return 0; };
321 int Module::OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text) { return 0; };
322 int Module::OnUserPreNotice(userrec* user,void* dest,int target_type, std::string &text) { return 0; };
323 int Module::OnUserPreNick(userrec* user, std::string newnick) { return 0; };
324 void Module::OnUserPostNick(userrec* user, std::string oldnick) { };
325 int Module::OnAccessCheck(userrec* source,userrec* dest,chanrec* channel,int access_type) { return ACR_DEFAULT; };
326 string_list Module::OnUserSync(userrec* user) { string_list empty; return empty; }
327 string_list Module::OnChannelSync(chanrec* chan) { string_list empty; return empty; }
328 void Module::On005Numeric(std::string &output) { };
329 int Module::OnKill(userrec* source, userrec* dest, std::string reason) { return 0; };
330 void Module::OnLoadModule(Module* mod,std::string name) { };
331 void Module::OnBackgroundTimer(time_t curtime) { };
332 void Module::OnSendList(userrec* user, chanrec* channel, char mode) { };
333 int Module::OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user) { return 0; };
334 bool Module::OnCheckReady(userrec* user) { return true; };
335 void Module::OnUserRegister(userrec* user) { };
336 int Module::OnUserPreKick(userrec* source, userrec* user, chanrec* chan, std::string reason) { return 0; };
337 void Module::OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason) { };
338 int Module::OnRawMode(userrec* user, chanrec* chan, char mode, std::string param, bool adding, int pcnt) { return 0; };
339 int Module::OnCheckInvite(userrec* user, chanrec* chan) { return 0; };
340 int Module::OnCheckKey(userrec* user, chanrec* chan, std::string keygiven) { return 0; };
341 int Module::OnCheckLimit(userrec* user, chanrec* chan) { return 0; };
342 int Module::OnCheckBan(userrec* user, chanrec* chan) { return 0; };
343 void Module::OnStats(char symbol) { };
344 int Module::OnChangeLocalUserHost(userrec* user, std::string newhost) { return 0; };
345 int Module::OnChangeLocalUserGECOS(userrec* user, std::string newhost) { return 0; };
346 int Module::OnLocalTopicChange(userrec* user, chanrec* chan, std::string topic) { return 0; };
347 int Module::OnMeshToken(char token,string_list params,serverrec* source,serverrec* reply, std::string tcp_host,std::string ipaddr,int port) { return 0; };
348 void Module::OnEvent(Event* event) { return; };
349 char* Module::OnRequest(Request* request) { return NULL; };
350 int Module::OnOperCompare(std::string password, std::string input) { return 0; };
351 void Module::OnGlobalOper(userrec* user) { };
352 void Module::OnGlobalConnect(userrec* user) { };
353 int Module::OnAddBan(userrec* source, chanrec* channel,std::string banmask) { return 0; };
354 int Module::OnDelBan(userrec* source, chanrec* channel,std::string banmask) { return 0; };
355 void Module::OnRawSocketAccept(int fd, std::string ip, int localport) { };
356 int Module::OnRawSocketWrite(int fd, char* buffer, int count) { return 0; };
357 void Module::OnRawSocketClose(int fd) { };
358 int Module::OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { return 0; };
360 // server is a wrapper class that provides methods to all of the C-style
361 // exports in the core
372 void Server::SendOpers(std::string s)
374 WriteOpers("%s",s.c_str());
377 bool Server::MatchText(std::string sliteral, std::string spattern)
379 char literal[MAXBUF],pattern[MAXBUF];
380 strlcpy(literal,sliteral.c_str(),MAXBUF);
381 strlcpy(pattern,spattern.c_str(),MAXBUF);
382 return match(literal,pattern);
385 void Server::SendToModeMask(std::string modes, int flags, std::string text)
387 WriteMode(modes.c_str(),flags,"%s",text.c_str());
390 chanrec* Server::JoinUserToChannel(userrec* user, std::string cname, std::string key)
392 return add_channel(user,cname.c_str(),key.c_str(),false);
395 chanrec* Server::PartUserFromChannel(userrec* user, std::string cname, std::string reason)
397 return del_channel(user,cname.c_str(),reason.c_str(),false);
400 chanuserlist Server::GetUsers(chanrec* chan)
404 std::vector<char*> *list = chan->GetUsers();
405 for (std::vector<char*>::iterator i = list->begin(); i != list->end(); i++)
408 userl.push_back((userrec*)o);
412 void Server::ChangeUserNick(userrec* user, std::string nickname)
414 force_nickchange(user,nickname.c_str());
417 void Server::QuitUser(userrec* user, std::string reason)
419 kill_link(user,reason.c_str());
422 bool Server::IsUlined(std::string server)
424 return is_uline(server.c_str());
427 void Server::CallCommandHandler(std::string commandname, char** parameters, int pcnt, userrec* user)
429 call_handler(commandname.c_str(),parameters,pcnt,user);
432 void Server::Log(int level, std::string s)
434 log(level,"%s",s.c_str());
437 void Server::AddCommand(char* cmd, handlerfunc f, char flags, int minparams, char* source)
439 createcommand(cmd,f,flags,minparams,source);
442 void Server::SendMode(char **parameters, int pcnt, userrec *user)
444 server_mode(parameters,pcnt,user);
447 void Server::Send(int Socket, std::string s)
449 Write(Socket,"%s",s.c_str());
452 void Server::SendServ(int Socket, std::string s)
454 WriteServ(Socket,"%s",s.c_str());
457 void Server::SendFrom(int Socket, userrec* User, std::string s)
459 WriteFrom(Socket,User,"%s",s.c_str());
462 void Server::SendTo(userrec* Source, userrec* Dest, std::string s)
466 // if source is NULL, then the message originates from the local server
467 Write(Dest->fd,":%s %s",this->GetServerName().c_str(),s.c_str());
471 // otherwise it comes from the user specified
472 WriteTo(Source,Dest,"%s",s.c_str());
476 void Server::SendChannelServerNotice(std::string ServName, chanrec* Channel, std::string text)
478 WriteChannelWithServ((char*)ServName.c_str(), Channel, "%s", text.c_str());
481 void Server::SendChannel(userrec* User, chanrec* Channel, std::string s,bool IncludeSender)
485 WriteChannel(Channel,User,"%s",s.c_str());
489 ChanExceptSender(Channel,User,"%s",s.c_str());
493 bool Server::CommonChannels(userrec* u1, userrec* u2)
495 return (common_channels(u1,u2) != 0);
498 void Server::SendCommon(userrec* User, std::string text,bool IncludeSender)
502 WriteCommon(User,"%s",text.c_str());
506 WriteCommonExcept(User,"%s",text.c_str());
510 void Server::SendWallops(userrec* User, std::string text)
512 WriteWallOps(User,false,"%s",text.c_str());
515 void Server::ChangeHost(userrec* user, std::string host)
517 ChangeDisplayedHost(user,host.c_str());
520 void Server::ChangeGECOS(userrec* user, std::string gecos)
522 ChangeName(user,gecos.c_str());
525 bool Server::IsNick(std::string nick)
527 return (isnick(nick.c_str()) != 0);
530 userrec* Server::FindNick(std::string nick)
535 userrec* Server::FindDescriptor(int socket)
537 return (socket < 65536 ? fd_ref_table[socket] : NULL);
540 chanrec* Server::FindChannel(std::string channel)
542 return FindChan(channel.c_str());
545 std::string Server::ChanMode(userrec* User, chanrec* Chan)
547 return cmode(User,Chan);
550 bool Server::IsOnChannel(userrec* User, chanrec* Chan)
552 return has_channel(User,Chan);
555 std::string Server::GetServerName()
557 return getservername();
560 std::string Server::GetNetworkName()
562 return getnetworkname();
565 std::string Server::GetServerDescription()
567 return getserverdesc();
570 Admin Server::GetAdmin()
572 return Admin(getadminname(),getadminemail(),getadminnick());
577 bool Server::AddExtendedMode(char modechar, int type, bool requires_oper, int params_when_on, int params_when_off)
579 if (((modechar >= 'A') && (modechar <= 'Z')) || ((modechar >= 'a') && (modechar <= 'z')))
581 if (type == MT_SERVER)
583 log(DEBUG,"*** API ERROR *** Modes of type MT_SERVER are reserved for future expansion");
586 if (((params_when_on>0) || (params_when_off>0)) && (type == MT_CLIENT))
588 log(DEBUG,"*** API ERROR *** Parameters on MT_CLIENT modes are not supported");
591 if ((params_when_on>1) || (params_when_off>1))
593 log(DEBUG,"*** API ERROR *** More than one parameter for an MT_CHANNEL mode is not yet supported");
596 return DoAddExtendedMode(modechar,type,requires_oper,params_when_on,params_when_off);
600 log(DEBUG,"*** API ERROR *** Muppet modechar detected.");
605 bool Server::AddExtendedListMode(char modechar)
607 bool res = DoAddExtendedMode(modechar,MT_CHANNEL,false,1,1);
609 ModeMakeList(modechar);
613 int Server::CountUsers(chanrec* c)
619 bool Server::UserToPseudo(userrec* user,std::string message)
621 unsigned int old_fd = user->fd;
622 user->fd = FD_MAGIC_NUMBER;
624 Write(old_fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,message.c_str());
627 EV_SET(&ke, old_fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
628 int i = kevent(kq, &ke, 1, 0, 0, NULL);
631 log(DEBUG,"kqueue: Failed to remove user from queue!");
635 struct epoll_event ev;
636 ev.events = EPOLLIN | EPOLLET;
638 int i = epoll_ctl(ep, EPOLL_CTL_DEL, old_fd, &ev);
641 log(DEBUG,"epoll: List deletion failure!");
649 bool Server::PseudoToUser(userrec* alive,userrec* zombie,std::string message)
651 zombie->fd = alive->fd;
652 alive->fd = FD_MAGIC_NUMBER;
653 alive->ClearBuffer();
654 Write(zombie->fd,":%s!%s@%s NICK %s",alive->nick,alive->ident,alive->host,zombie->nick);
655 kill_link(alive,message.c_str());
656 fd_ref_table[zombie->fd] = zombie;
657 for (int i = 0; i != MAXCHANS; i++)
659 if (zombie->chans[i].channel != NULL)
661 if (zombie->chans[i].channel->name)
663 chanrec* Ptr = zombie->chans[i].channel;
664 WriteFrom(zombie->fd,zombie,"JOIN %s",Ptr->name);
667 WriteServ(zombie->fd,"332 %s %s :%s", zombie->nick, Ptr->name, Ptr->topic);
668 WriteServ(zombie->fd,"333 %s %s %s %d", zombie->nick, Ptr->name, Ptr->setby, Ptr->topicset);
670 userlist(zombie,Ptr);
671 WriteServ(zombie->fd,"366 %s %s :End of /NAMES list.", zombie->nick, Ptr->name);
679 void Server::AddGLine(long duration, std::string source, std::string reason, std::string hostmask)
681 add_gline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
684 void Server::AddQLine(long duration, std::string source, std::string reason, std::string nickname)
686 add_qline(duration, source.c_str(), reason.c_str(), nickname.c_str());
689 void Server::AddZLine(long duration, std::string source, std::string reason, std::string ipaddr)
691 add_zline(duration, source.c_str(), reason.c_str(), ipaddr.c_str());
694 void Server::AddKLine(long duration, std::string source, std::string reason, std::string hostmask)
696 add_kline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
699 void Server::AddELine(long duration, std::string source, std::string reason, std::string hostmask)
701 add_eline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
704 bool Server::DelGLine(std::string hostmask)
706 del_gline(hostmask.c_str());
709 bool Server::DelQLine(std::string nickname)
711 del_qline(nickname.c_str());
714 bool Server::DelZLine(std::string ipaddr)
716 del_zline(ipaddr.c_str());
719 bool Server::DelKLine(std::string hostmask)
721 del_kline(hostmask.c_str());
724 bool Server::DelELine(std::string hostmask)
726 del_eline(hostmask.c_str());
729 long Server::CalcDuration(std::string delta)
731 return duration(delta.c_str());
734 bool Server::IsValidMask(std::string mask)
736 const char* dest = mask.c_str();
737 if (strchr(dest,'!')==0)
739 if (strchr(dest,'@')==0)
741 for (int i = 0; i < strlen(dest); i++)
744 for (int i = 0; i < strlen(dest); i++)
748 for (int i = 0; i < strlen(dest); i++)
754 for (int i = 0; i < strlen(dest); i++)
763 void Server::MeshSendAll(std::string text)
765 NetSendToAll((char*)text.c_str());
768 void Server::MeshSendCommon(userrec* user, std::string text)
771 NetSendToCommon(user,(char*)text.c_str());
774 void Server::MeshSendAllAlive(std::string text)
776 NetSendToAllAlive((char*)text.c_str());
779 void Server::MeshSendUnicast(std::string destination, std::string text)
781 NetSendToOne((char*)destination.c_str(),(char*)text.c_str());
784 void Server::MeshSendAllExcept(std::string target, std::string text)
786 NetSendToAllExcept(target.c_str(),(char*)text.c_str());
789 bool Server::MeshCheckChan(chanrec *c,std::string servername)
793 return ChanAnyOnThisServer(c,(char*)servername.c_str());
798 bool Server::MeshCheckCommon(userrec* u,std::string servername)
802 return CommonOnThisServer(u,(char*)servername.c_str());
807 Module* Server::FindModule(std::string name)
809 for (int i = 0; i <= MODCOUNT; i++)
811 if (module_names[i] == name)
819 ConfigReader::ConfigReader()
821 this->cache = new std::stringstream(std::stringstream::in | std::stringstream::out);
822 this->errorlog = new std::stringstream(std::stringstream::in | std::stringstream::out);
823 this->readerror = LoadConf(CONFIG_FILE,this->cache,this->errorlog);
824 if (!this->readerror)
825 this->error = CONF_FILE_NOT_FOUND;
829 ConfigReader::~ConfigReader()
834 delete this->errorlog;
838 ConfigReader::ConfigReader(std::string filename)
840 this->cache = new std::stringstream(std::stringstream::in | std::stringstream::out);
841 this->errorlog = new std::stringstream(std::stringstream::in | std::stringstream::out);
842 this->readerror = LoadConf(filename.c_str(),this->cache,this->errorlog);
843 if (!this->readerror)
844 this->error = CONF_FILE_NOT_FOUND;
847 std::string ConfigReader::ReadValue(std::string tag, std::string name, int index)
852 strlcpy(t,tag.c_str(),MAXBUF);
853 strlcpy(n,name.c_str(),MAXBUF);
854 int res = ReadConf(cache,t,n,index,val);
857 this->error = CONF_VALUE_NOT_FOUND;
863 bool ConfigReader::ReadFlag(std::string tag, std::string name, int index)
868 strlcpy(t,tag.c_str(),MAXBUF);
869 strlcpy(n,name.c_str(),MAXBUF);
870 int res = ReadConf(cache,t,n,index,val);
873 this->error = CONF_VALUE_NOT_FOUND;
877 return ((s == "yes") || (s == "YES") || (s == "true") || (s == "TRUE") || (s == "1"));
880 long ConfigReader::ReadInteger(std::string tag, std::string name, int index, bool needs_unsigned)
885 strlcpy(t,tag.c_str(),MAXBUF);
886 strlcpy(n,name.c_str(),MAXBUF);
887 int res = ReadConf(cache,t,n,index,val);
890 this->error = CONF_VALUE_NOT_FOUND;
893 for (int i = 0; i < strlen(val); i++)
895 if (!isdigit(val[i]))
897 this->error = CONF_NOT_A_NUMBER;
901 if ((needs_unsigned) && (atoi(val)<0))
903 this->error = CONF_NOT_UNSIGNED;
909 long ConfigReader::GetError()
911 long olderr = this->error;
916 void ConfigReader::DumpErrors(bool bail, userrec* user)
920 printf("There were errors in your configuration:\n%s",errorlog->str().c_str());
928 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
929 while (!errorlog->eof())
931 errorlog->getline(dataline,1024);
932 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
937 WriteOpers("There were errors in the configuration file:",user->nick);
938 while (!errorlog->eof())
940 errorlog->getline(dataline,1024);
941 WriteOpers(dataline);
949 int ConfigReader::Enumerate(std::string tag)
951 return EnumConf(cache,tag.c_str());
954 int ConfigReader::EnumerateValues(std::string tag, int index)
956 return EnumValues(cache, tag.c_str(), index);
959 bool ConfigReader::Verify()
961 return this->readerror;
965 FileReader::FileReader(std::string filename)
968 readfile(c,filename.c_str());
972 FileReader::FileReader()
976 void FileReader::LoadFile(std::string filename)
979 readfile(c,filename.c_str());
984 FileReader::~FileReader()
988 bool FileReader::Exists()
1000 std::string FileReader::GetLine(int x)
1002 if ((x<0) || (x>fc.size()))
1007 int FileReader::FileSize()
1013 std::vector<Module*> modules(255);
1014 std::vector<ircd_module*> factory(255);