1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 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 * ---------------------------------------------------
17 /* Now with added unF! ;) */
21 #include "inspircd_config.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.h"
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
33 #include <ext/hash_map>
55 #include "inspstring.h"
57 #include "helperfuncs.h"
59 #include "socketengine.h"
60 #include "userprocess.h"
65 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
66 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
68 time_t startup_time = time(NULL);
70 extern std::vector<Module*> modules;
71 extern std::vector<ircd_module*> factory;
73 std::vector<InspSocket*> module_sockets;
76 int openSockfd[MAXSOCKS];
77 struct sockaddr_in client,server;
80 extern InspSocket* socket_ref[65535];
82 time_t TIME = time(NULL), OLDTIME = time(NULL);
84 SocketEngine* SE = NULL;
86 // This table references users by file descriptor.
87 // its an array to make it VERY fast, as all lookups are referenced
88 // by an integer, meaning there is no need for a scan/search operation.
89 userrec* fd_ref_table[65536];
91 serverstats* stats = new serverstats;
92 Server* MyServer = new Server;
93 ServerConfig *Config = new ServerConfig;
98 command_table cmdlist;
100 servernamelist servernames;
101 int boundPortCount = 0;
102 int portCount = 0, ports[MAXSOCKS];
103 std::vector<userrec*> all_opers;
107 void AddOper(userrec* user)
109 log(DEBUG,"Oper added to optimization list");
110 all_opers.push_back(user);
113 void AddServerName(std::string servername)
115 log(DEBUG,"Adding server name: %s",servername.c_str());
116 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
118 if (*a == servername)
121 servernames.push_back(servername);
124 const char* FindServerNamePtr(std::string servername)
126 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
128 if (*a == servername)
131 AddServerName(servername);
132 return FindServerNamePtr(servername);
135 void DeleteOper(userrec* user)
137 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
141 log(DEBUG,"Oper removed from optimization list");
148 std::string GetRevision()
150 /* w00t got me to replace a bunch of strtok_r
151 * with something nicer, so i did this. Its the
152 * same thing really, only in C++. It places the
153 * text into a std::stringstream which is a readable
154 * and writeable buffer stream, and then pops two
155 * words off it, space delimited. Because it reads
156 * into the same variable twice, the first word
157 * is discarded, and the second one returned.
159 std::stringstream Revision("$Revision$");
161 Revision >> single >> single;
166 /* add a channel to a user, creating the record for it if needed and linking
167 * it to the user record */
169 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
171 if ((!user) || (!cn))
173 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
180 strncpy(cname,cn,CHANMAX);
182 log(DEBUG,"add_channel: %s %s",user->nick,cname);
184 chanrec* Ptr = FindChan(cname);
191 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
195 /* create a new one */
196 chanlist[cname] = new chanrec();
197 strlcpy(chanlist[cname]->name, cname,CHANMAX);
198 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
199 chanlist[cname]->created = TIME;
200 strcpy(chanlist[cname]->topic, "");
201 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
202 chanlist[cname]->topicset = 0;
203 Ptr = chanlist[cname];
204 log(DEBUG,"add_channel: created: %s",cname);
205 /* set created to 2 to indicate user
206 * is the first in the channel
207 * and should be given ops */
212 /* Already on the channel */
213 if (has_channel(user,Ptr))
216 // remote users are allowed us to bypass channel modes
217 // and bans (used by servers)
221 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
231 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
236 log(DEBUG,"add_channel: no key given in JOIN");
237 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
242 if (strcasecmp(key,Ptr->key))
244 log(DEBUG,"add_channel: bad key given in JOIN");
245 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
251 if (Ptr->binarymodes & CM_INVITEONLY)
254 FOREACH_RESULT(OnCheckInvite(user, Ptr));
257 log(DEBUG,"add_channel: channel is +i");
258 if (user->IsInvited(Ptr->name))
260 /* user was invited to channel */
261 /* there may be an optional channel NOTICE here */
265 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
269 user->RemoveInvite(Ptr->name);
274 FOREACH_RESULT(OnCheckLimit(user, Ptr));
277 if (usercount(Ptr) >= Ptr->limit)
279 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
284 if (Ptr->bans.size())
286 log(DEBUG,"add_channel: about to walk banlist");
288 FOREACH_RESULT(OnCheckBan(user, Ptr));
291 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
293 if (match(user->GetFullHost(),i->data))
295 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
305 log(DEBUG,"Overridden checks");
310 log(DEBUG,"Passed channel checks");
312 for (unsigned int index =0; index < user->chans.size(); index++)
314 if (user->chans[index].channel == NULL)
316 return ForceChan(Ptr,user->chans[index],user,created);
319 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
320 * and put the channel in here. Same for remote users which are not bound by
321 * the channel limits. Otherwise, nope, youre boned.
326 chanrec* c = ForceChan(Ptr,a,user,created);
327 user->chans.push_back(a);
330 else if (strchr(user->modes,'o'))
332 /* Oper allows extension up to the OPERMAXCHANS value */
333 if (user->chans.size() < OPERMAXCHANS)
336 chanrec* c = ForceChan(Ptr,a,user,created);
337 user->chans.push_back(a);
341 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
342 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
346 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
350 /* first user in is given ops */
351 a.uc_modes = UCMODE_OP;
358 Ptr->AddUser((char*)user);
359 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
360 log(DEBUG,"Sent JOIN to client");
363 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
364 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
367 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
368 FOREACH_MOD OnUserJoin(user,Ptr);
372 /* remove a channel from a users record, and remove the record from memory
373 * if the channel has become empty */
375 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
377 if ((!user) || (!cname))
379 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
383 chanrec* Ptr = FindChan(cname);
388 FOREACH_MOD OnUserPart(user,Ptr);
389 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
391 for (unsigned int i =0; i < user->chans.size(); i++)
393 /* zap it from the channel list of the user */
394 if (user->chans[i].channel == Ptr)
398 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
402 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
404 user->chans[i].uc_modes = 0;
405 user->chans[i].channel = NULL;
406 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
411 Ptr->DelUser((char*)user);
413 /* if there are no users left on the channel */
416 chan_hash::iterator iter = chanlist.find(Ptr->name);
418 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
420 /* kill the record */
421 if (iter != chanlist.end())
423 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
425 chanlist.erase(iter);
433 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
435 if ((!src) || (!user) || (!Ptr) || (!reason))
437 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
441 if ((!Ptr) || (!user) || (!src))
446 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
448 if (!has_channel(user,Ptr))
450 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
455 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
456 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
459 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
461 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
463 if (cstatus(src,Ptr) == STATUS_HOP)
465 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
469 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
476 if (!is_uline(src->server))
479 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
484 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
486 for (unsigned int i =0; i < user->chans.size(); i++)
488 /* zap it from the channel list of the user */
489 if (user->chans[i].channel)
490 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
492 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
493 user->chans[i].uc_modes = 0;
494 user->chans[i].channel = NULL;
495 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
500 Ptr->DelUser((char*)user);
502 /* if there are no users left on the channel */
505 chan_hash::iterator iter = chanlist.find(Ptr->name);
507 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
509 /* kill the record */
510 if (iter != chanlist.end())
512 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
514 chanlist.erase(iter);
522 /* This function pokes and hacks at a parameter list like the following:
524 * PART #winbot,#darkgalaxy :m00!
526 * to turn it into a series of individual calls like this:
529 * PART #darkgalaxy :m00!
531 * The seperate calls are sent to a callback function provided by the caller
532 * (the caller will usually call itself recursively). The callback function
533 * must be a command handler. Calling this function on a line with no list causes
534 * no action to be taken. You must provide a starting and ending parameter number
535 * where the range of the list can be found, useful if you have a terminating
536 * parameter as above which is actually not part of the list, or parameters
537 * before the actual list as well. This code is used by many functions which
538 * can function as "one to list" (see the RFC) */
540 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
545 char blog[32][MAXBUF];
546 char blog2[32][MAXBUF];
547 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
551 for (int i = 0; i <32; i++)
554 for (int i = 0; i <32; i++)
558 for (int i = 0; i <10; i++)
567 if (pcnt > 1) /* we have a key to copy */
569 strlcpy(keystr,parameters[1],MAXBUF);
573 if (!parameters[start])
577 if (!strchr(parameters[start],','))
582 for (int i = start; i <= end; i++)
586 strlcat(plist,parameters[i],MAXBUF);
594 for (int i = 0; i < t; i++)
599 strlcpy(blog[j++],param,MAXBUF);
603 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
608 strlcpy(blog[j++],param,MAXBUF);
611 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
616 if ((joins) && (keystr))
618 if (strchr(keystr,','))
623 for (int i = 0; i < t2; i++)
625 if (keystr[i] == ',')
628 strlcpy(blog2[j++],param,MAXBUF);
632 strlcpy(blog2[j++],param,MAXBUF);
637 for (j = 0; j < total; j++)
643 for (q = end; q < pcnt-1; q++)
647 pars[q-end+1] = parameters[q+1];
650 if ((joins) && (parameters[1]))
661 /* repeatedly call the function with the hacked parameter list */
662 if ((joins) && (pcnt > 1))
666 // pars[1] already set up and containing key from blog2[j]
671 pars[1] = parameters[1];
677 fn(pars,pcnt-(end-start),u);
686 void kill_link(userrec *user,const char* r)
688 user_hash::iterator iter = clientlist.find(user->nick);
692 strncpy(reason,r,MAXBUF);
694 if (strlen(reason)>MAXQUIT)
696 reason[MAXQUIT-1] = '\0';
699 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
700 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
701 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
703 if (user->registered == 7) {
704 FOREACH_MOD OnUserQuit(user,reason);
705 WriteCommonExcept(user,"QUIT :%s",reason);
708 user->FlushWriteBuf();
710 FOREACH_MOD OnUserDisconnect(user);
714 FOREACH_MOD OnRawSocketClose(user->fd);
719 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
720 // if they were an oper with +s.
721 if (user->registered == 7) {
722 purge_empty_chans(user);
723 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
725 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
729 if (iter != clientlist.end())
731 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
733 fd_ref_table[user->fd] = NULL;
734 clientlist.erase(iter);
739 void kill_link_silent(userrec *user,const char* r)
741 user_hash::iterator iter = clientlist.find(user->nick);
745 strncpy(reason,r,MAXBUF);
747 if (strlen(reason)>MAXQUIT)
749 reason[MAXQUIT-1] = '\0';
752 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
753 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
754 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
756 user->FlushWriteBuf();
758 if (user->registered == 7) {
759 FOREACH_MOD OnUserQuit(user,reason);
760 WriteCommonExcept(user,"QUIT :%s",reason);
763 FOREACH_MOD OnUserDisconnect(user);
767 FOREACH_MOD OnRawSocketClose(user->fd);
772 if (user->registered == 7) {
773 purge_empty_chans(user);
776 if (iter != clientlist.end())
778 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
780 fd_ref_table[user->fd] = NULL;
781 clientlist.erase(iter);
787 int main(int argc, char** argv)
791 log(DEBUG,"*** InspIRCd starting up!");
792 if (!FileExists(CONFIG_FILE))
794 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
795 log(DEFAULT,"main: no config");
796 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
800 for (int i = 1; i < argc; i++)
802 if (!strcmp(argv[i],"-nofork")) {
803 Config->nofork = true;
805 if (!strcmp(argv[i],"-wait")) {
808 if (!strcmp(argv[i],"-nolimit")) {
809 Config->unlimitcore = true;
814 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
816 // initialize the lowercase mapping table
817 for (unsigned int cn = 0; cn < 256; cn++)
819 // lowercase the uppercase chars
820 for (unsigned int cn = 65; cn < 91; cn++)
821 lowermap[cn] = tolower(cn);
822 // now replace the specific chars for scandanavian comparison
823 lowermap[(unsigned)'['] = '{';
824 lowermap[(unsigned)']'] = '}';
825 lowermap[(unsigned)'\\'] = '|';
827 if (InspIRCd(argv,argc) == ERROR)
829 log(DEFAULT,"main: daemon function bailed");
830 printf("ERROR: could not initialise. Shutting down.\n");
837 template<typename T> inline string ConvToStr(const T &in)
840 if (!(tmp << in)) return string();
844 /* re-allocates a nick in the user_hash after they change nicknames,
845 * returns a pointer to the new user as it may have moved */
847 userrec* ReHashNick(char* Old, char* New)
849 //user_hash::iterator newnick;
850 user_hash::iterator oldnick = clientlist.find(Old);
852 log(DEBUG,"ReHashNick: %s %s",Old,New);
854 if (!strcasecmp(Old,New))
856 log(DEBUG,"old nick is new nick, skipping");
857 return oldnick->second;
860 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
862 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
864 userrec* olduser = oldnick->second;
865 clientlist[New] = olduser;
866 clientlist.erase(oldnick);
868 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
870 return clientlist[New];
873 /* adds or updates an entry in the whowas list */
874 void AddWhoWas(userrec* u)
876 whowas_hash::iterator iter = whowas.find(u->nick);
877 WhoWasUser *a = new WhoWasUser();
878 strlcpy(a->nick,u->nick,NICKMAX);
879 strlcpy(a->ident,u->ident,IDENTMAX);
880 strlcpy(a->dhost,u->dhost,160);
881 strlcpy(a->host,u->host,160);
882 strlcpy(a->fullname,u->fullname,MAXGECOS);
883 strlcpy(a->server,u->server,256);
884 a->signon = u->signon;
886 /* MAX_WHOWAS: max number of /WHOWAS items
887 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
888 * can be replaced by a newer one
891 if (iter == whowas.end())
893 if (whowas.size() >= (unsigned)WHOWAS_MAX)
895 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
897 // 3600 seconds in an hour ;)
898 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
900 // delete the old one
901 if (i->second) delete i->second;
902 // replace with new one
904 log(DEBUG,"added WHOWAS entry, purged an old record");
908 // no space left and user doesnt exist. Don't leave ram in use!
909 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
914 log(DEBUG,"added fresh WHOWAS entry");
920 log(DEBUG,"updated WHOWAS entry");
921 if (iter->second) delete iter->second;
927 void* dns_task(void* arg)
929 userrec* u = (userrec*)arg;
930 log(DEBUG,"DNS thread for user %s",u->nick);
935 if (dns1.ReverseLookup(u->ip))
937 log(DEBUG,"DNS Step 1");
938 while (!dns1.HasResult())
942 host = dns1.GetResult();
945 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
946 if (dns2.ForwardLookup(host))
948 while (!dns2.HasResult())
952 ip = dns2.GetResultIP();
953 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
954 if (ip == std::string(u->ip))
956 log(DEBUG,"DNS Step 4");
957 if (host.length() < 160)
959 log(DEBUG,"DNS Step 5");
960 strcpy(u->host,host.c_str());
961 strcpy(u->dhost,host.c_str());
972 /* add a client connection to the sockets list */
973 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
977 user_hash::iterator iter;
979 tempnick = ConvToStr(socket) + "-unknown";
980 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
982 iter = clientlist.find(tempnick);
985 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
986 // using one as a registered connection. As theyre per fd, we can also safely assume
987 // that we wont have collisions. Therefore, if the nick exists in the list, its only
988 // used by a dead socket, erase the iterator so that the new client may reclaim it.
989 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
990 // issue in earlier alphas/betas
991 if (iter != clientlist.end())
993 userrec* goner = iter->second;
995 clientlist.erase(iter);
999 * It is OK to access the value here this way since we know
1000 * it exists, we just created it above.
1002 * At NO other time should you access a value in a map or a
1003 * hash_map this way.
1005 clientlist[tempnick] = new userrec();
1007 NonBlocking(socket);
1008 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1010 clientlist[tempnick]->fd = socket;
1011 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1012 strlcpy(clientlist[tempnick]->host, host,160);
1013 strlcpy(clientlist[tempnick]->dhost, host,160);
1014 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
1015 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1016 clientlist[tempnick]->registered = 0;
1017 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
1018 clientlist[tempnick]->lastping = 1;
1019 clientlist[tempnick]->port = port;
1020 strlcpy(clientlist[tempnick]->ip,ip,16);
1022 // set the registration timeout for this user
1023 unsigned long class_regtimeout = 90;
1024 int class_flood = 0;
1025 long class_threshold = 5;
1026 long class_sqmax = 262144; // 256kb
1027 long class_rqmax = 4096; // 4k
1029 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
1031 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1033 class_regtimeout = (unsigned long)i->registration_timeout;
1034 class_flood = i->flood;
1035 clientlist[tempnick]->pingmax = i->pingtime;
1036 class_threshold = i->threshold;
1037 class_sqmax = i->sendqmax;
1038 class_rqmax = i->recvqmax;
1043 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
1044 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1045 clientlist[tempnick]->flood = class_flood;
1046 clientlist[tempnick]->threshold = class_threshold;
1047 clientlist[tempnick]->sendqmax = class_sqmax;
1048 clientlist[tempnick]->recvqmax = class_rqmax;
1053 for (int i = 0; i < MAXCHANS; i++)
1054 clientlist[tempnick]->chans.push_back(a);
1056 if (clientlist.size() > Config->SoftLimit)
1058 kill_link(clientlist[tempnick],"No more connections allowed");
1062 if (clientlist.size() >= MAXCLIENTS)
1064 kill_link(clientlist[tempnick],"No more connections allowed");
1068 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1069 // its a pretty big but for the moment valid assumption:
1070 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1071 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1072 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1073 // which for the time being is a physical impossibility (even the largest networks dont have more
1074 // than about 10,000 users on ONE server!)
1075 if ((unsigned)socket > 65534)
1077 kill_link(clientlist[tempnick],"Server is full");
1082 char* e = matches_exception(ip);
1085 char* r = matches_zline(ip);
1088 char reason[MAXBUF];
1089 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1090 kill_link(clientlist[tempnick],reason);
1094 fd_ref_table[socket] = clientlist[tempnick];
1095 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1098 /* shows the message of the day, and any other on-logon stuff */
1099 void FullConnectUser(userrec* user)
1101 stats->statsConnects++;
1102 user->idle_lastmsg = TIME;
1103 log(DEBUG,"ConnectUser: %s",user->nick);
1105 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1107 kill_link(user,"Invalid password");
1112 kill_link(user,"Unauthorised connection");
1116 char match_against[MAXBUF];
1117 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1118 char* e = matches_exception(match_against);
1121 char* r = matches_gline(match_against);
1124 char reason[MAXBUF];
1125 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1126 kill_link_silent(user,reason);
1129 r = matches_kline(user->host);
1132 char reason[MAXBUF];
1133 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1134 kill_link_silent(user,reason);
1140 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1141 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
1142 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1143 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1144 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
1145 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1146 std::stringstream v;
1147 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1148 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1149 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1150 v << Config->Network;
1151 std::string data005 = v.str();
1152 FOREACH_MOD On005Numeric(data005);
1153 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1154 // so i'd better split it :)
1155 std::stringstream out(data005);
1156 std::string token = "";
1157 std::string line5 = "";
1158 int token_counter = 0;
1162 line5 = line5 + token + " ";
1164 if ((token_counter >= 13) || (out.eof() == true))
1166 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1173 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1174 // onto the network and produce 'fake direction'
1175 FOREACH_MOD OnUserConnect(user);
1176 FOREACH_MOD OnGlobalConnect(user);
1177 user->registered = 7;
1178 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1182 /* shows the message of the day, and any other on-logon stuff */
1183 void ConnectUser(userrec *user)
1185 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1186 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1188 FullConnectUser(user);
1192 std::string GetVersionString()
1194 char versiondata[MAXBUF];
1196 char dnsengine[] = "multithread";
1198 char dnsengine[] = "singlethread";
1200 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1204 void handle_version(char **parameters, int pcnt, userrec *user)
1206 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1210 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1212 for (unsigned int i = 0; i < cmdlist.size(); i++)
1214 if (!strcasecmp(cmdlist[i].command,commandname))
1216 if (cmdlist[i].handler_function)
1218 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1220 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1222 if (cmdlist[i].flags_needed)
1224 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1242 // calls a handler function for a command
1244 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1246 for (unsigned int i = 0; i < cmdlist.size(); i++)
1248 if (!strcasecmp(cmdlist[i].command,commandname))
1250 if (cmdlist[i].handler_function)
1252 if (pcnt>=cmdlist[i].min_params)
1254 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1256 if (cmdlist[i].flags_needed)
1258 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1260 cmdlist[i].handler_function(parameters,pcnt,user);
1265 cmdlist[i].handler_function(parameters,pcnt,user);
1275 void force_nickchange(userrec* user,const char* newnick)
1282 FOREACH_RESULT(OnUserPreNick(user,newnick));
1284 stats->statsCollisions++;
1285 kill_link(user,"Nickname collision");
1288 if (matches_qline(newnick))
1290 stats->statsCollisions++;
1291 kill_link(user,"Nickname collision");
1299 strncpy(nick,newnick,MAXBUF);
1301 if (user->registered == 7)
1305 handle_nick(pars,1,user);
1311 int process_parameters(char **command_p,char *parameters)
1314 int q = strlen(parameters);
1317 /* no parameters, command_p invalid! */
1320 if (parameters[0] == ':')
1322 command_p[0] = parameters+1;
1327 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1329 /* only one parameter */
1330 command_p[0] = parameters;
1331 if (parameters[0] == ':')
1333 if (strchr(parameters,' ') != NULL)
1341 command_p[j++] = parameters;
1342 for (int i = 0; i <= q; i++)
1344 if (parameters[i] == ' ')
1346 command_p[j++] = parameters+i+1;
1347 parameters[i] = '\0';
1348 if (command_p[j-1][0] == ':')
1350 *command_p[j-1]++; /* remove dodgy ":" */
1352 /* parameter like this marks end of the sequence */
1356 return j; /* returns total number of items in the list */
1359 void process_command(userrec *user, char* cmd)
1363 char *command_p[127];
1364 char p[MAXBUF], temp[MAXBUF];
1365 int j, items, cmd_found;
1367 for (int i = 0; i < 127; i++)
1368 command_p[i] = NULL;
1383 int total_params = 0;
1386 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1388 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1391 // found a 'trailing', we dont count them after this.
1399 // another phidjit bug...
1400 if (total_params > 126)
1402 *(strchr(cmd,' ')) = '\0';
1403 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1407 strlcpy(temp,cmd,MAXBUF);
1409 std::string tmp = cmd;
1410 for (int i = 0; i <= MODCOUNT; i++)
1412 std::string oldtmp = tmp;
1413 modules[i]->OnServerRaw(tmp,true,user);
1416 log(DEBUG,"A Module changed the input string!");
1417 log(DEBUG,"New string: %s",tmp.c_str());
1418 log(DEBUG,"Old string: %s",oldtmp.c_str());
1422 strlcpy(cmd,tmp.c_str(),MAXBUF);
1423 strlcpy(temp,cmd,MAXBUF);
1425 if (!strchr(cmd,' '))
1427 /* no parameters, lets skip the formalities and not chop up
1429 log(DEBUG,"About to preprocess command with no params");
1431 command_p[0] = NULL;
1433 for (unsigned int i = 0; i <= strlen(cmd); i++)
1435 cmd[i] = toupper(cmd[i]);
1443 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1444 for (unsigned int i = 0; i < strlen(temp); i++)
1446 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1452 /* split the full string into a command plus parameters */
1456 if (strchr(cmd,' '))
1458 for (unsigned int i = 0; i <= strlen(cmd); i++)
1460 /* capitalise the command ONLY, leave params intact */
1461 cmd[i] = toupper(cmd[i]);
1462 /* are we nearly there yet?! :P */
1466 parameters = cmd+i+1;
1474 for (unsigned int i = 0; i <= strlen(cmd); i++)
1476 cmd[i] = toupper(cmd[i]);
1483 if (strlen(command)>MAXCOMMAND)
1485 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1489 for (unsigned int x = 0; x < strlen(command); x++)
1491 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1493 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1495 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1497 stats->statsUnknown++;
1498 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1505 for (unsigned int i = 0; i != cmdlist.size(); i++)
1507 if (cmdlist[i].command[0])
1509 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1515 items = process_parameters(command_p,parameters);
1520 command_p[0] = NULL;
1526 command_p[0] = NULL;
1531 /* activity resets the ping pending timer */
1532 user->nping = TIME + user->pingmax;
1533 if ((items) < cmdlist[i].min_params)
1535 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1536 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1539 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1541 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1542 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1546 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1548 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1549 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1553 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1555 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1557 if ((!isnick(user->nick)) || (user->registered != 7))
1559 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1560 WriteServ(user->fd,"451 %s :You have not registered",command);
1564 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1566 std::stringstream dcmds(Config->DisabledCommands);
1567 while (!dcmds.eof())
1569 std::string thiscmd;
1571 if (!strcasecmp(thiscmd.c_str(),command))
1573 // command is disabled!
1574 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1579 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1581 if (cmdlist[i].handler_function)
1584 /* ikky /stats counters */
1587 cmdlist[i].use_count++;
1588 cmdlist[i].total_bytes+=strlen(temp);
1592 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1593 if (MOD_RESULT == 1) {
1597 /* WARNING: nothing may come after the
1598 * command handler call, as the handler
1599 * may free the user structure! */
1601 cmdlist[i].handler_function(command_p,items,user);
1607 WriteServ(user->fd,"451 %s :You have not registered",command);
1615 if ((!cmd_found) && (user))
1617 stats->statsUnknown++;
1618 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1622 bool removecommands(const char* source)
1624 bool go_again = true;
1628 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1630 if (!strcmp(i->source,source))
1632 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1643 void process_buffer(const char* cmdbuf,userrec *user)
1647 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1653 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1660 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1662 strlcpy(cmd,cmdbuf,MAXBUF);
1667 int sl = strlen(cmd)-1;
1668 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1673 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1678 while (cmd[sl] == ' ') // strip trailing spaces
1688 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
1690 if ((user) && (cmd))
1692 process_command(user,cmd);
1696 char MODERR[MAXBUF];
1703 void erase_factory(int j)
1706 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
1711 factory.push_back(NULL);
1718 void erase_module(int j)
1721 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
1727 modules.push_back(NULL);
1733 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
1737 Config->module_names.erase(v);
1745 bool UnloadModule(const char* filename)
1747 std::string filename_str = filename;
1748 for (unsigned int j = 0; j != Config->module_names.size(); j++)
1750 if (Config->module_names[j] == filename_str)
1752 if (modules[j]->GetVersion().Flags & VF_STATIC)
1754 log(DEFAULT,"Failed to unload STATIC module %s",filename);
1755 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
1758 /* Give the module a chance to tidy out all its metadata */
1759 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1761 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
1763 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1765 modules[j]->OnCleanup(TYPE_USER,u->second);
1767 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
1769 log(DEBUG,"Deleting module...");
1771 log(DEBUG,"Erasing module entry...");
1773 log(DEBUG,"Removing dependent commands...");
1774 removecommands(filename);
1775 log(DEFAULT,"Module %s unloaded",filename);
1780 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
1781 snprintf(MODERR,MAXBUF,"Module not loaded");
1785 bool LoadModule(const char* filename)
1787 char modfile[MAXBUF];
1789 snprintf(modfile,MAXBUF,"%s",filename);
1791 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
1793 std::string filename_str = filename;
1795 if (!DirValid(modfile))
1797 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
1798 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
1802 log(DEBUG,"Loading module: %s",modfile);
1804 if (FileExists(modfile))
1807 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1809 if (Config->module_names[j] == filename_str)
1811 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
1812 snprintf(MODERR,MAXBUF,"Module already loaded");
1816 ircd_module* a = new ircd_module(modfile);
1817 factory[MODCOUNT+1] = a;
1818 if (factory[MODCOUNT+1]->LastError())
1820 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
1821 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
1825 if (factory[MODCOUNT+1]->factory)
1827 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
1828 modules[MODCOUNT+1] = m;
1829 /* save the module and the module's classfactory, if
1830 * this isnt done, random crashes can occur :/ */
1831 Config->module_names.push_back(filename);
1835 log(DEFAULT,"Unable to load %s",modfile);
1836 snprintf(MODERR,MAXBUF,"Factory function failed!");
1843 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1844 snprintf(MODERR,MAXBUF,"Module file could not be found");
1849 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
1855 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1856 int clientportcount = 0;
1857 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1859 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1860 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1861 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1862 if (strcmp(Type,"servers"))
1864 // modules handle server bind types now,
1865 // its not a typo in the strcmp.
1866 ports[clientportcount] = atoi(configToken);
1867 strlcpy(Config->addrs[clientportcount],Addr,256);
1869 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1872 portCount = clientportcount;
1874 for (int count = 0; count < portCount; count++)
1876 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
1878 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
1881 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],Config->addrs[count]) == ERROR)
1883 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
1885 else /* well we at least bound to one socket so we'll continue */
1891 /* if we didn't bind to anything then abort */
1892 if (!boundPortCount)
1894 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1895 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
1899 return boundPortCount;
1902 int InspIRCd(char** argv, int argc)
1904 bool expire_run = false;
1905 std::vector<int> activefds;
1909 InspSocket* s = NULL;
1910 InspSocket* s_del = NULL;
1912 unsigned int numberactive;
1913 sockaddr_in sock_us; // our port number
1914 socklen_t uslen; // length of our port number
1916 /* Beta 7 moved all this stuff out of the main function
1917 * into smaller sub-functions, much tidier -- Brain
1919 OpenLog(argv, argc);
1920 Config->ClearStack();
1921 Config->Read(true,NULL);
1923 SetupCommandTable();
1924 AddServerName(Config->ServerName);
1926 boundPortCount = BindPorts();
1929 startup_time = time(NULL);
1931 if (!Config->nofork)
1933 if (DaemonSeed() == ERROR)
1935 printf("ERROR: could not go into daemon mode. Shutting down.\n");
1940 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
1941 * initialize the socket engine.
1943 SE = new SocketEngine();
1945 /* We must load the modules AFTER initializing the socket engine, now */
1948 printf("\nInspIRCd is now running!\n");
1949 if (!Config->nofork)
1951 freopen("/dev/null","w",stdout);
1952 freopen("/dev/null","w",stderr);
1955 /* Add the listening sockets used for client inbound connections
1956 * to the socket engine
1958 for (int count = 0; count < portCount; count++)
1959 SE->AddFd(openSockfd[count],true,X_LISTEN);
1961 WritePID(Config->PID);
1963 /* main loop, this never returns */
1966 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1967 * Once per loop iteration is pleanty.
1972 /* Run background module timers every few seconds
1973 * (the docs say modules shouldnt rely on accurate
1974 * timing using this event, so we dont have to
1975 * time this exactly).
1977 if (((TIME % 8) == 0) && (!expire_run))
1980 FOREACH_MOD OnBackgroundTimer(TIME);
1984 if ((TIME % 8) == 1)
1987 /* Once a second, do the background processing */
1988 if (TIME != OLDTIME)
1989 while (DoBackgroundUserStuff(TIME));
1991 /* Call the socket engine to wait on the active
1992 * file descriptors. The socket engine has everything's
1993 * descriptors in its list... dns, modules, users,
1994 * servers... so its nice and easy, just one call.
1996 SE->Wait(activefds);
1999 * Now process each of the fd's. For users, we have a fast
2000 * lookup table which can find a user by file descriptor, so
2001 * processing them by fd isnt expensive. If we have a lot of
2002 * listening ports or module sockets though, things could get
2005 numberactive = activefds.size();
2006 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2008 int socket_type = SE->GetType(activefds[activefd]);
2009 switch (socket_type)
2011 case X_ESTAB_CLIENT:
2013 cu = fd_ref_table[activefds[activefd]];
2019 case X_ESTAB_MODULE:
2021 /* Process module-owned sockets.
2022 * Modules are encouraged to inherit their sockets from
2023 * InspSocket so we can process them neatly like this.
2025 s = socket_ref[activefds[activefd]];
2027 if ((s) && (!s->Poll()))
2029 log(DEBUG,"Socket poll returned false, close and bail");
2030 SE->DelFd(s->GetFd());
2031 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2033 s_del = (InspSocket*)*a;
2034 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2036 module_sockets.erase(a);
2048 /* When we are using single-threaded dns,
2049 * the sockets for dns end up in our mainloop.
2050 * When we are using multi-threaded dns,
2051 * each thread has its own basic poll() loop
2052 * within it, making them 'fire and forget'
2053 * and independent of the mainloop.
2055 #ifndef THREADED_DNS
2056 dns_poll(activefds[activefd]);
2062 /* It's a listener */
2063 uslen = sizeof(sock_us);
2064 length = sizeof(client);
2065 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2066 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2068 in_port = ntohs(sock_us.sin_port);
2069 log(DEBUG,"Accepted socket %d",incomingSockfd);
2070 target = (char*)inet_ntoa(client.sin_addr);
2071 /* Years and years ago, we used to resolve here
2072 * using gethostbyaddr(). That is sucky and we
2073 * don't do that any more...
2075 if (incomingSockfd >= 0)
2077 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2078 stats->statsAccept++;
2079 AddClient(incomingSockfd, target, in_port, false, target);
2080 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2084 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2085 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2086 stats->statsRefused++;
2091 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2092 shutdown(incomingSockfd,2);
2093 close(incomingSockfd);
2098 /* Something went wrong if we're in here.
2099 * In fact, so wrong, im not quite sure
2100 * what we would do, so for now, its going
2101 * to safely do bugger all.
2108 /* This is never reached -- we hope! */