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 * ---------------------------------------------------
18 #include "inspircd_io.h"
19 #include "inspircd_util.h"
20 #include "inspircd_config.h"
23 #include <sys/errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
27 #include <sys/types.h>
28 #include <sys/event.h>
35 #include <ext/hash_map>
47 #include "connection.h"
59 #include "inspstring.h"
60 #include "helperfuncs.h"
70 extern std::vector<Module*> modules;
71 extern std::vector<ircd_module*> factory;
76 extern char ServerName[MAXBUF];
77 extern char Network[MAXBUF];
78 extern char ServerDesc[MAXBUF];
79 extern char AdminName[MAXBUF];
80 extern char AdminEmail[MAXBUF];
81 extern char AdminNick[MAXBUF];
82 extern char diepass[MAXBUF];
83 extern char restartpass[MAXBUF];
84 extern char motd[MAXBUF];
85 extern char rules[MAXBUF];
86 extern char list[MAXBUF];
87 extern char PrefixQuit[MAXBUF];
88 extern char DieValue[MAXBUF];
91 extern int WHOWAS_STALE;
92 extern int WHOWAS_MAX;
94 extern time_t startup_time;
95 extern int NetBufferSize;
96 extern int MaxWhoResults;
97 extern time_t nb_start;
99 extern std::vector<int> fd_reap;
100 extern std::vector<std::string> module_names;
102 extern int boundPortCount;
103 extern int portCount;
104 extern int SERVERportCount;
105 extern int ports[MAXSOCKS];
106 extern int defaultRoute;
108 extern std::vector<long> auth_cookies;
109 extern std::stringstream config_f;
111 extern serverrec* me[32];
113 extern FILE *log_file;
115 extern userrec* fd_ref_table[65536];
117 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
118 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
119 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
120 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, StrHashComp> whowas_hash;
121 typedef std::deque<command_t> command_table;
124 extern user_hash clientlist;
125 extern chan_hash chanlist;
126 extern whowas_hash whowas;
127 extern command_table cmdlist;
128 extern file_cache MOTD;
129 extern file_cache RULES;
130 extern address_cache IP;
133 // class type for holding an extended mode character - internal to core
135 class ExtMode : public classbase
144 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) { };
147 typedef std::vector<ExtMode> ExtModeList;
148 typedef ExtModeList::iterator ExtModeListIter;
153 // returns true if an extended mode character is in use
154 bool ModeDefined(char modechar, int type)
156 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
158 if ((i->modechar == modechar) && (i->type == type))
166 bool ModeIsListMode(char modechar, int type)
168 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
170 if ((i->modechar == modechar) && (i->type == type) && (i->list == true))
178 bool ModeDefinedOper(char modechar, int type)
180 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
182 if ((i->modechar == modechar) && (i->type == type) && (i->needsoper == true))
190 // returns number of parameters for a custom mode when it is switched on
191 int ModeDefinedOn(char modechar, int type)
193 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
195 if ((i->modechar == modechar) && (i->type == type))
197 return i->params_when_on;
203 // returns number of parameters for a custom mode when it is switched on
204 int ModeDefinedOff(char modechar, int type)
206 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
208 if ((i->modechar == modechar) && (i->type == type))
210 return i->params_when_off;
216 // returns true if an extended mode character is in use
217 bool DoAddExtendedMode(char modechar, int type, bool requires_oper, int params_on, int params_off)
219 if (ModeDefined(modechar,type)) {
222 EMode.push_back(ExtMode(modechar,type,requires_oper,params_on,params_off));
226 // turns a mode into a listmode
227 void ModeMakeList(char modechar)
229 for (ExtModeListIter i = EMode.begin(); i < EMode.end(); i++)
231 if ((i->modechar == modechar) && (i->type == MT_CHANNEL))
240 // version is a simple class for holding a modules version number
242 Version::Version(int major, int minor, int revision, int build, int flags) : Major(major), Minor(minor), Revision(revision), Build(build), Flags(flags) { };
244 // admin is a simple class for holding a server's administrative info
246 Admin::Admin(std::string name, std::string email, std::string nick) : Name(name), Email(email), Nick(nick) { };
248 Request::Request(char* anydata, Module* src, Module* dst) : data(anydata), source(src), dest(dst) { };
250 char* Request::GetData()
255 Module* Request::GetSource()
260 Module* Request::GetDest()
265 char* Request::Send()
269 return dest->OnRequest(this);
277 Event::Event(char* anydata, Module* src, std::string eventid) : data(anydata), source(src), id(eventid) { };
279 char* Event::GetData()
284 Module* Event::GetSource()
291 FOREACH_MOD OnEvent(this);
295 std::string Event::GetEventID()
301 // These declarations define the behavours of the base class Module (which does nothing at all)
303 Module::~Module() { }
304 void Module::OnUserConnect(userrec* user) { }
305 void Module::OnUserQuit(userrec* user) { }
306 void Module::OnUserDisconnect(userrec* user) { }
307 void Module::OnUserJoin(userrec* user, chanrec* channel) { }
308 void Module::OnUserPart(userrec* user, chanrec* channel) { }
309 void Module::OnPacketTransmit(std::string &data, std::string serv) { }
310 void Module::OnPacketReceive(std::string &data, std::string serv) { }
311 void Module::OnRehash() { }
312 void Module::OnServerRaw(std::string &raw, bool inbound, userrec* user) { }
313 int Module::OnUserPreJoin(userrec* user, chanrec* chan, const char* cname) { return 0; }
314 int Module::OnExtendedMode(userrec* user, void* target, char modechar, int type, bool mode_on, string_list ¶ms) { return false; }
315 Version Module::GetVersion() { return Version(1,0,0,0,VF_VENDOR); }
316 void Module::OnOper(userrec* user) { };
317 void Module::OnInfo(userrec* user) { };
318 void Module::OnWhois(userrec* source, userrec* dest) { };
319 int Module::OnUserPreInvite(userrec* source,userrec* dest,chanrec* channel) { return 0; };
320 int Module::OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text) { return 0; };
321 int Module::OnUserPreNotice(userrec* user,void* dest,int target_type, std::string &text) { return 0; };
322 int Module::OnUserPreNick(userrec* user, std::string newnick) { return 0; };
323 void Module::OnUserPostNick(userrec* user, std::string oldnick) { };
324 int Module::OnAccessCheck(userrec* source,userrec* dest,chanrec* channel,int access_type) { return ACR_DEFAULT; };
325 string_list Module::OnUserSync(userrec* user) { string_list empty; return empty; }
326 string_list Module::OnChannelSync(chanrec* chan) { string_list empty; return empty; }
327 void Module::On005Numeric(std::string &output) { };
328 int Module::OnKill(userrec* source, userrec* dest, std::string reason) { return 0; };
329 void Module::OnLoadModule(Module* mod,std::string name) { };
330 void Module::OnBackgroundTimer(time_t curtime) { };
331 void Module::OnSendList(userrec* user, chanrec* channel, char mode) { };
332 int Module::OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user) { return 0; };
333 bool Module::OnCheckReady(userrec* user) { return true; };
334 void Module::OnUserRegister(userrec* user) { };
335 int Module::OnUserPreKick(userrec* source, userrec* user, chanrec* chan, std::string reason) { return 0; };
336 void Module::OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason) { };
337 int Module::OnRawMode(userrec* user, chanrec* chan, char mode, std::string param, bool adding, int pcnt) { return 0; };
338 int Module::OnCheckInvite(userrec* user, chanrec* chan) { return 0; };
339 int Module::OnCheckKey(userrec* user, chanrec* chan, std::string keygiven) { return 0; };
340 int Module::OnCheckLimit(userrec* user, chanrec* chan) { return 0; };
341 int Module::OnCheckBan(userrec* user, chanrec* chan) { return 0; };
342 void Module::OnStats(char symbol) { };
343 int Module::OnChangeLocalUserHost(userrec* user, std::string newhost) { return 0; };
344 int Module::OnChangeLocalUserGECOS(userrec* user, std::string newhost) { return 0; };
345 int Module::OnLocalTopicChange(userrec* user, chanrec* chan, std::string topic) { return 0; };
346 int Module::OnMeshToken(char token,string_list params,serverrec* source,serverrec* reply, std::string tcp_host,std::string ipaddr,int port) { return 0; };
347 void Module::OnEvent(Event* event) { return; };
348 char* Module::OnRequest(Request* request) { return NULL; };
349 int Module::OnOperCompare(std::string password, std::string input) { return 0; };
350 void Module::OnGlobalOper(userrec* user) { };
351 void Module::OnGlobalConnect(userrec* user) { };
352 int Module::OnAddBan(userrec* source, chanrec* channel,std::string banmask) { return 0; };
353 int Module::OnDelBan(userrec* source, chanrec* channel,std::string banmask) { return 0; };
354 void Module::OnRawSocketAccept(int fd, std::string ip, int localport) { };
355 int Module::OnRawSocketWrite(int fd, char* buffer, int count) { return 0; };
356 void Module::OnRawSocketClose(int fd) { };
357 int Module::OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { return 0; };
359 // server is a wrapper class that provides methods to all of the C-style
360 // exports in the core
371 void Server::SendOpers(std::string s)
373 WriteOpers("%s",s.c_str());
376 bool Server::MatchText(std::string sliteral, std::string spattern)
378 char literal[MAXBUF],pattern[MAXBUF];
379 strlcpy(literal,sliteral.c_str(),MAXBUF);
380 strlcpy(pattern,spattern.c_str(),MAXBUF);
381 return match(literal,pattern);
384 void Server::SendToModeMask(std::string modes, int flags, std::string text)
386 WriteMode(modes.c_str(),flags,"%s",text.c_str());
389 chanrec* Server::JoinUserToChannel(userrec* user, std::string cname, std::string key)
391 return add_channel(user,cname.c_str(),key.c_str(),false);
394 chanrec* Server::PartUserFromChannel(userrec* user, std::string cname, std::string reason)
396 return del_channel(user,cname.c_str(),reason.c_str(),false);
399 chanuserlist Server::GetUsers(chanrec* chan)
403 std::vector<char*> *list = chan->GetUsers();
404 for (std::vector<char*>::iterator i = list->begin(); i != list->end(); i++)
407 userl.push_back((userrec*)o);
411 void Server::ChangeUserNick(userrec* user, std::string nickname)
413 force_nickchange(user,nickname.c_str());
416 void Server::QuitUser(userrec* user, std::string reason)
418 kill_link(user,reason.c_str());
421 bool Server::IsUlined(std::string server)
423 return is_uline(server.c_str());
426 void Server::CallCommandHandler(std::string commandname, char** parameters, int pcnt, userrec* user)
428 call_handler(commandname.c_str(),parameters,pcnt,user);
431 void Server::Log(int level, std::string s)
433 log(level,"%s",s.c_str());
436 void Server::AddCommand(char* cmd, handlerfunc f, char flags, int minparams, char* source)
438 createcommand(cmd,f,flags,minparams,source);
441 void Server::SendMode(char **parameters, int pcnt, userrec *user)
443 server_mode(parameters,pcnt,user);
446 void Server::Send(int Socket, std::string s)
448 Write(Socket,"%s",s.c_str());
451 void Server::SendServ(int Socket, std::string s)
453 WriteServ(Socket,"%s",s.c_str());
456 void Server::SendFrom(int Socket, userrec* User, std::string s)
458 WriteFrom(Socket,User,"%s",s.c_str());
461 void Server::SendTo(userrec* Source, userrec* Dest, std::string s)
465 // if source is NULL, then the message originates from the local server
466 Write(Dest->fd,":%s %s",this->GetServerName().c_str(),s.c_str());
470 // otherwise it comes from the user specified
471 WriteTo(Source,Dest,"%s",s.c_str());
475 void Server::SendChannelServerNotice(std::string ServName, chanrec* Channel, std::string text)
477 WriteChannelWithServ((char*)ServName.c_str(), Channel, "%s", text.c_str());
480 void Server::SendChannel(userrec* User, chanrec* Channel, std::string s,bool IncludeSender)
484 WriteChannel(Channel,User,"%s",s.c_str());
488 ChanExceptSender(Channel,User,"%s",s.c_str());
492 bool Server::CommonChannels(userrec* u1, userrec* u2)
494 return (common_channels(u1,u2) != 0);
497 void Server::SendCommon(userrec* User, std::string text,bool IncludeSender)
501 WriteCommon(User,"%s",text.c_str());
505 WriteCommonExcept(User,"%s",text.c_str());
509 void Server::SendWallops(userrec* User, std::string text)
511 WriteWallOps(User,false,"%s",text.c_str());
514 void Server::ChangeHost(userrec* user, std::string host)
516 ChangeDisplayedHost(user,host.c_str());
519 void Server::ChangeGECOS(userrec* user, std::string gecos)
521 ChangeName(user,gecos.c_str());
524 bool Server::IsNick(std::string nick)
526 return (isnick(nick.c_str()) != 0);
529 userrec* Server::FindNick(std::string nick)
534 userrec* Server::FindDescriptor(int socket)
536 return (socket < 65536 ? fd_ref_table[socket] : NULL);
539 chanrec* Server::FindChannel(std::string channel)
541 return FindChan(channel.c_str());
544 std::string Server::ChanMode(userrec* User, chanrec* Chan)
546 return cmode(User,Chan);
549 bool Server::IsOnChannel(userrec* User, chanrec* Chan)
551 return has_channel(User,Chan);
554 std::string Server::GetServerName()
556 return getservername();
559 std::string Server::GetNetworkName()
561 return getnetworkname();
564 std::string Server::GetServerDescription()
566 return getserverdesc();
569 Admin Server::GetAdmin()
571 return Admin(getadminname(),getadminemail(),getadminnick());
576 bool Server::AddExtendedMode(char modechar, int type, bool requires_oper, int params_when_on, int params_when_off)
578 if (((modechar >= 'A') && (modechar <= 'Z')) || ((modechar >= 'a') && (modechar <= 'z')))
580 if (type == MT_SERVER)
582 log(DEBUG,"*** API ERROR *** Modes of type MT_SERVER are reserved for future expansion");
585 if (((params_when_on>0) || (params_when_off>0)) && (type == MT_CLIENT))
587 log(DEBUG,"*** API ERROR *** Parameters on MT_CLIENT modes are not supported");
590 if ((params_when_on>1) || (params_when_off>1))
592 log(DEBUG,"*** API ERROR *** More than one parameter for an MT_CHANNEL mode is not yet supported");
595 return DoAddExtendedMode(modechar,type,requires_oper,params_when_on,params_when_off);
599 log(DEBUG,"*** API ERROR *** Muppet modechar detected.");
604 bool Server::AddExtendedListMode(char modechar)
606 bool res = DoAddExtendedMode(modechar,MT_CHANNEL,false,1,1);
608 ModeMakeList(modechar);
612 int Server::CountUsers(chanrec* c)
618 bool Server::UserToPseudo(userrec* user,std::string message)
620 unsigned int old_fd = user->fd;
621 user->fd = FD_MAGIC_NUMBER;
623 Write(old_fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,message.c_str());
626 EV_SET(&ke, old_fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
627 int i = kevent(kq, &ke, 1, 0, 0, NULL);
630 log(DEBUG,"kqueue: Failed to remove user from queue!");
637 bool Server::PseudoToUser(userrec* alive,userrec* zombie,std::string message)
639 zombie->fd = alive->fd;
640 alive->fd = FD_MAGIC_NUMBER;
641 alive->ClearBuffer();
642 Write(zombie->fd,":%s!%s@%s NICK %s",alive->nick,alive->ident,alive->host,zombie->nick);
643 kill_link(alive,message.c_str());
644 fd_ref_table[zombie->fd] = zombie;
645 for (int i = 0; i != MAXCHANS; i++)
647 if (zombie->chans[i].channel != NULL)
649 if (zombie->chans[i].channel->name)
651 chanrec* Ptr = zombie->chans[i].channel;
652 WriteFrom(zombie->fd,zombie,"JOIN %s",Ptr->name);
655 WriteServ(zombie->fd,"332 %s %s :%s", zombie->nick, Ptr->name, Ptr->topic);
656 WriteServ(zombie->fd,"333 %s %s %s %d", zombie->nick, Ptr->name, Ptr->setby, Ptr->topicset);
658 userlist(zombie,Ptr);
659 WriteServ(zombie->fd,"366 %s %s :End of /NAMES list.", zombie->nick, Ptr->name);
667 void Server::AddGLine(long duration, std::string source, std::string reason, std::string hostmask)
669 add_gline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
672 void Server::AddQLine(long duration, std::string source, std::string reason, std::string nickname)
674 add_qline(duration, source.c_str(), reason.c_str(), nickname.c_str());
677 void Server::AddZLine(long duration, std::string source, std::string reason, std::string ipaddr)
679 add_zline(duration, source.c_str(), reason.c_str(), ipaddr.c_str());
682 void Server::AddKLine(long duration, std::string source, std::string reason, std::string hostmask)
684 add_kline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
687 void Server::AddELine(long duration, std::string source, std::string reason, std::string hostmask)
689 add_eline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
692 bool Server::DelGLine(std::string hostmask)
694 del_gline(hostmask.c_str());
697 bool Server::DelQLine(std::string nickname)
699 del_qline(nickname.c_str());
702 bool Server::DelZLine(std::string ipaddr)
704 del_zline(ipaddr.c_str());
707 bool Server::DelKLine(std::string hostmask)
709 del_kline(hostmask.c_str());
712 bool Server::DelELine(std::string hostmask)
714 del_eline(hostmask.c_str());
717 long Server::CalcDuration(std::string delta)
719 return duration(delta.c_str());
722 bool Server::IsValidMask(std::string mask)
724 const char* dest = mask.c_str();
725 if (strchr(dest,'!')==0)
727 if (strchr(dest,'@')==0)
729 for (int i = 0; i < strlen(dest); i++)
732 for (int i = 0; i < strlen(dest); i++)
736 for (int i = 0; i < strlen(dest); i++)
742 for (int i = 0; i < strlen(dest); i++)
751 void Server::MeshSendAll(std::string text)
753 NetSendToAll((char*)text.c_str());
756 void Server::MeshSendCommon(userrec* user, std::string text)
759 NetSendToCommon(user,(char*)text.c_str());
762 void Server::MeshSendAllAlive(std::string text)
764 NetSendToAllAlive((char*)text.c_str());
767 void Server::MeshSendUnicast(std::string destination, std::string text)
769 NetSendToOne((char*)destination.c_str(),(char*)text.c_str());
772 void Server::MeshSendAllExcept(std::string target, std::string text)
774 NetSendToAllExcept(target.c_str(),(char*)text.c_str());
777 bool Server::MeshCheckChan(chanrec *c,std::string servername)
781 return ChanAnyOnThisServer(c,(char*)servername.c_str());
786 bool Server::MeshCheckCommon(userrec* u,std::string servername)
790 return CommonOnThisServer(u,(char*)servername.c_str());
795 Module* Server::FindModule(std::string name)
797 for (int i = 0; i <= MODCOUNT; i++)
799 if (module_names[i] == name)
807 ConfigReader::ConfigReader()
809 this->cache = new std::stringstream(std::stringstream::in | std::stringstream::out);
810 this->errorlog = new std::stringstream(std::stringstream::in | std::stringstream::out);
811 this->readerror = LoadConf(CONFIG_FILE,this->cache,this->errorlog);
812 if (!this->readerror)
813 this->error = CONF_FILE_NOT_FOUND;
817 ConfigReader::~ConfigReader()
822 delete this->errorlog;
826 ConfigReader::ConfigReader(std::string filename)
828 this->cache = new std::stringstream(std::stringstream::in | std::stringstream::out);
829 this->errorlog = new std::stringstream(std::stringstream::in | std::stringstream::out);
830 this->readerror = LoadConf(filename.c_str(),this->cache,this->errorlog);
831 if (!this->readerror)
832 this->error = CONF_FILE_NOT_FOUND;
835 std::string ConfigReader::ReadValue(std::string tag, std::string name, int index)
840 strlcpy(t,tag.c_str(),MAXBUF);
841 strlcpy(n,name.c_str(),MAXBUF);
842 int res = ReadConf(cache,t,n,index,val);
845 this->error = CONF_VALUE_NOT_FOUND;
851 bool ConfigReader::ReadFlag(std::string tag, std::string name, int index)
856 strlcpy(t,tag.c_str(),MAXBUF);
857 strlcpy(n,name.c_str(),MAXBUF);
858 int res = ReadConf(cache,t,n,index,val);
861 this->error = CONF_VALUE_NOT_FOUND;
865 return ((s == "yes") || (s == "YES") || (s == "true") || (s == "TRUE") || (s == "1"));
868 long ConfigReader::ReadInteger(std::string tag, std::string name, int index, bool needs_unsigned)
873 strlcpy(t,tag.c_str(),MAXBUF);
874 strlcpy(n,name.c_str(),MAXBUF);
875 int res = ReadConf(cache,t,n,index,val);
878 this->error = CONF_VALUE_NOT_FOUND;
881 for (int i = 0; i < strlen(val); i++)
883 if (!isdigit(val[i]))
885 this->error = CONF_NOT_A_NUMBER;
889 if ((needs_unsigned) && (atoi(val)<0))
891 this->error = CONF_NOT_UNSIGNED;
897 long ConfigReader::GetError()
899 long olderr = this->error;
904 void ConfigReader::DumpErrors(bool bail, userrec* user)
908 printf("There were errors in your configuration:\n%s",errorlog->str().c_str());
916 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
917 while (!errorlog->eof())
919 errorlog->getline(dataline,1024);
920 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
925 WriteOpers("There were errors in the configuration file:",user->nick);
926 while (!errorlog->eof())
928 errorlog->getline(dataline,1024);
929 WriteOpers(dataline);
937 int ConfigReader::Enumerate(std::string tag)
939 return EnumConf(cache,tag.c_str());
942 int ConfigReader::EnumerateValues(std::string tag, int index)
944 return EnumValues(cache, tag.c_str(), index);
947 bool ConfigReader::Verify()
949 return this->readerror;
953 FileReader::FileReader(std::string filename)
956 readfile(c,filename.c_str());
960 FileReader::FileReader()
964 void FileReader::LoadFile(std::string filename)
967 readfile(c,filename.c_str());
972 FileReader::~FileReader()
976 bool FileReader::Exists()
988 std::string FileReader::GetLine(int x)
990 if ((x<0) || (x>fc.size()))
995 int FileReader::FileSize()
1001 std::vector<Module*> modules(255);
1002 std::vector<ircd_module*> factory(255);