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;
101 servernamelist servernames;
103 int boundPortCount = 0;
104 int portCount = 0, ports[MAXSOCKS];
108 /*int has_channel(userrec *u, chanrec *c);
109 int usercount(chanrec *c);
110 int usercount_i(chanrec *c);
111 char* Passwd(userrec *user);
112 bool IsDenied(userrec *user);
113 void AddWhoWas(userrec* u);*/
115 std::vector<userrec*> all_opers;
119 void AddOper(userrec* user)
121 log(DEBUG,"Oper added to optimization list");
122 all_opers.push_back(user);
125 void AddServerName(std::string servername)
127 log(DEBUG,"Adding server name: %s",servername.c_str());
128 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
130 if (*a == servername)
133 servernames.push_back(servername);
136 const char* FindServerNamePtr(std::string servername)
138 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
140 if (*a == servername)
143 AddServerName(servername);
144 return FindServerNamePtr(servername);
147 void DeleteOper(userrec* user)
149 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
153 log(DEBUG,"Oper removed from optimization list");
160 std::string GetRevision()
162 /* w00t got me to replace a bunch of strtok_r
163 * with something nicer, so i did this. Its the
164 * same thing really, only in C++. It places the
165 * text into a std::stringstream which is a readable
166 * and writeable buffer stream, and then pops two
167 * words off it, space delimited. Because it reads
168 * into the same variable twice, the first word
169 * is discarded, and the second one returned.
171 std::stringstream Revision("$Revision$");
173 Revision >> single >> single;
178 std::string getservername()
180 return Config->ServerName;
183 std::string getserverdesc()
185 return Config->ServerDesc;
188 std::string getnetworkname()
190 return Config->Network;
193 std::string getadminname()
195 return Config->AdminName;
198 std::string getadminemail()
200 return Config->AdminEmail;
203 std::string getadminnick()
205 return Config->AdminNick;
208 /* add a channel to a user, creating the record for it if needed and linking
209 * it to the user record */
211 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
213 if ((!user) || (!cn))
215 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
222 strncpy(cname,cn,CHANMAX);
224 log(DEBUG,"add_channel: %s %s",user->nick,cname);
226 chanrec* Ptr = FindChan(cname);
233 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
237 /* create a new one */
238 chanlist[cname] = new chanrec();
239 strlcpy(chanlist[cname]->name, cname,CHANMAX);
240 chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
241 chanlist[cname]->created = TIME;
242 strcpy(chanlist[cname]->topic, "");
243 strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
244 chanlist[cname]->topicset = 0;
245 Ptr = chanlist[cname];
246 log(DEBUG,"add_channel: created: %s",cname);
247 /* set created to 2 to indicate user
248 * is the first in the channel
249 * and should be given ops */
254 /* Already on the channel */
255 if (has_channel(user,Ptr))
258 // remote users are allowed us to bypass channel modes
259 // and bans (used by servers)
263 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
273 FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
278 log(DEBUG,"add_channel: no key given in JOIN");
279 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
284 if (strcasecmp(key,Ptr->key))
286 log(DEBUG,"add_channel: bad key given in JOIN");
287 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
293 if (Ptr->binarymodes & CM_INVITEONLY)
296 FOREACH_RESULT(OnCheckInvite(user, Ptr));
299 log(DEBUG,"add_channel: channel is +i");
300 if (user->IsInvited(Ptr->name))
302 /* user was invited to channel */
303 /* there may be an optional channel NOTICE here */
307 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
311 user->RemoveInvite(Ptr->name);
316 FOREACH_RESULT(OnCheckLimit(user, Ptr));
319 if (usercount(Ptr) >= Ptr->limit)
321 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
326 if (Ptr->bans.size())
328 log(DEBUG,"add_channel: about to walk banlist");
330 FOREACH_RESULT(OnCheckBan(user, Ptr));
333 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
335 if (match(user->GetFullHost(),i->data))
337 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
347 log(DEBUG,"Overridden checks");
352 log(DEBUG,"Passed channel checks");
354 for (unsigned int index =0; index < user->chans.size(); index++)
356 if (user->chans[index].channel == NULL)
358 return ForceChan(Ptr,user->chans[index],user,created);
361 /* XXX: If the user is an oper here, we can just extend their user->chans vector by one
362 * and put the channel in here. Same for remote users which are not bound by
363 * the channel limits. Otherwise, nope, youre boned.
368 chanrec* c = ForceChan(Ptr,a,user,created);
369 user->chans.push_back(a);
372 else if (strchr(user->modes,'o'))
374 /* Oper allows extension up to the OPERMAXCHANS value */
375 if (user->chans.size() < OPERMAXCHANS)
378 chanrec* c = ForceChan(Ptr,a,user,created);
379 user->chans.push_back(a);
383 log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
384 WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
388 chanrec* ForceChan(chanrec* Ptr,ucrec &a,userrec* user, int created)
392 /* first user in is given ops */
393 a.uc_modes = UCMODE_OP;
400 Ptr->AddUser((char*)user);
401 WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
402 log(DEBUG,"Sent JOIN to client");
405 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
406 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
409 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
410 FOREACH_MOD OnUserJoin(user,Ptr);
414 /* remove a channel from a users record, and remove the record from memory
415 * if the channel has become empty */
417 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
419 if ((!user) || (!cname))
421 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
425 chanrec* Ptr = FindChan(cname);
430 FOREACH_MOD OnUserPart(user,Ptr);
431 log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
433 for (unsigned int i =0; i < user->chans.size(); i++)
435 /* zap it from the channel list of the user */
436 if (user->chans[i].channel == Ptr)
440 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
444 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
446 user->chans[i].uc_modes = 0;
447 user->chans[i].channel = NULL;
448 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
453 Ptr->DelUser((char*)user);
455 /* if there are no users left on the channel */
458 chan_hash::iterator iter = chanlist.find(Ptr->name);
460 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
462 /* kill the record */
463 if (iter != chanlist.end())
465 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
467 chanlist.erase(iter);
475 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
477 if ((!src) || (!user) || (!Ptr) || (!reason))
479 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
483 if ((!Ptr) || (!user) || (!src))
488 log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
490 if (!has_channel(user,Ptr))
492 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
497 FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
498 if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
501 if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
503 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
505 if (cstatus(src,Ptr) == STATUS_HOP)
507 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
511 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
518 if (!is_uline(src->server))
521 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
526 FOREACH_MOD OnUserKick(src,user,Ptr,reason);
528 for (unsigned int i =0; i < user->chans.size(); i++)
530 /* zap it from the channel list of the user */
531 if (user->chans[i].channel)
532 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
534 WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
535 user->chans[i].uc_modes = 0;
536 user->chans[i].channel = NULL;
537 log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
542 Ptr->DelUser((char*)user);
544 /* if there are no users left on the channel */
547 chan_hash::iterator iter = chanlist.find(Ptr->name);
549 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
551 /* kill the record */
552 if (iter != chanlist.end())
554 log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
556 chanlist.erase(iter);
564 /* This function pokes and hacks at a parameter list like the following:
566 * PART #winbot,#darkgalaxy :m00!
568 * to turn it into a series of individual calls like this:
571 * PART #darkgalaxy :m00!
573 * The seperate calls are sent to a callback function provided by the caller
574 * (the caller will usually call itself recursively). The callback function
575 * must be a command handler. Calling this function on a line with no list causes
576 * no action to be taken. You must provide a starting and ending parameter number
577 * where the range of the list can be found, useful if you have a terminating
578 * parameter as above which is actually not part of the list, or parameters
579 * before the actual list as well. This code is used by many functions which
580 * can function as "one to list" (see the RFC) */
582 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
587 char blog[32][MAXBUF];
588 char blog2[32][MAXBUF];
589 int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
593 for (int i = 0; i <32; i++)
596 for (int i = 0; i <32; i++)
600 for (int i = 0; i <10; i++)
609 if (pcnt > 1) /* we have a key to copy */
611 strlcpy(keystr,parameters[1],MAXBUF);
615 if (!parameters[start])
619 if (!strchr(parameters[start],','))
624 for (int i = start; i <= end; i++)
628 strlcat(plist,parameters[i],MAXBUF);
636 for (int i = 0; i < t; i++)
641 strlcpy(blog[j++],param,MAXBUF);
645 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
650 strlcpy(blog[j++],param,MAXBUF);
653 if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
658 if ((joins) && (keystr))
660 if (strchr(keystr,','))
665 for (int i = 0; i < t2; i++)
667 if (keystr[i] == ',')
670 strlcpy(blog2[j++],param,MAXBUF);
674 strlcpy(blog2[j++],param,MAXBUF);
679 for (j = 0; j < total; j++)
685 for (q = end; q < pcnt-1; q++)
689 pars[q-end+1] = parameters[q+1];
692 if ((joins) && (parameters[1]))
703 /* repeatedly call the function with the hacked parameter list */
704 if ((joins) && (pcnt > 1))
708 // pars[1] already set up and containing key from blog2[j]
713 pars[1] = parameters[1];
719 fn(pars,pcnt-(end-start),u);
728 void kill_link(userrec *user,const char* r)
730 user_hash::iterator iter = clientlist.find(user->nick);
734 strncpy(reason,r,MAXBUF);
736 if (strlen(reason)>MAXQUIT)
738 reason[MAXQUIT-1] = '\0';
741 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
742 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
743 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
745 if (user->registered == 7) {
746 FOREACH_MOD OnUserQuit(user,reason);
747 WriteCommonExcept(user,"QUIT :%s",reason);
750 user->FlushWriteBuf();
752 FOREACH_MOD OnUserDisconnect(user);
756 FOREACH_MOD OnRawSocketClose(user->fd);
761 // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
762 // if they were an oper with +s.
763 if (user->registered == 7) {
764 purge_empty_chans(user);
765 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
767 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
771 if (iter != clientlist.end())
773 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
775 fd_ref_table[user->fd] = NULL;
776 clientlist.erase(iter);
781 void kill_link_silent(userrec *user,const char* r)
783 user_hash::iterator iter = clientlist.find(user->nick);
787 strncpy(reason,r,MAXBUF);
789 if (strlen(reason)>MAXQUIT)
791 reason[MAXQUIT-1] = '\0';
794 log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
795 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
796 log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
798 user->FlushWriteBuf();
800 if (user->registered == 7) {
801 FOREACH_MOD OnUserQuit(user,reason);
802 WriteCommonExcept(user,"QUIT :%s",reason);
805 FOREACH_MOD OnUserDisconnect(user);
809 FOREACH_MOD OnRawSocketClose(user->fd);
814 if (user->registered == 7) {
815 purge_empty_chans(user);
818 if (iter != clientlist.end())
820 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
822 fd_ref_table[user->fd] = NULL;
823 clientlist.erase(iter);
829 int main(int argc, char** argv)
833 log(DEBUG,"*** InspIRCd starting up!");
834 if (!FileExists(CONFIG_FILE))
836 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
837 log(DEFAULT,"main: no config");
838 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
842 for (int i = 1; i < argc; i++)
844 if (!strcmp(argv[i],"-nofork")) {
845 Config->nofork = true;
847 if (!strcmp(argv[i],"-wait")) {
850 if (!strcmp(argv[i],"-nolimit")) {
851 Config->unlimitcore = true;
856 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
858 // initialize the lowercase mapping table
859 for (unsigned int cn = 0; cn < 256; cn++)
861 // lowercase the uppercase chars
862 for (unsigned int cn = 65; cn < 91; cn++)
863 lowermap[cn] = tolower(cn);
864 // now replace the specific chars for scandanavian comparison
865 lowermap[(unsigned)'['] = '{';
866 lowermap[(unsigned)']'] = '}';
867 lowermap[(unsigned)'\\'] = '|';
869 if (InspIRCd(argv,argc) == ERROR)
871 log(DEFAULT,"main: daemon function bailed");
872 printf("ERROR: could not initialise. Shutting down.\n");
879 template<typename T> inline string ConvToStr(const T &in)
882 if (!(tmp << in)) return string();
886 /* re-allocates a nick in the user_hash after they change nicknames,
887 * returns a pointer to the new user as it may have moved */
889 userrec* ReHashNick(char* Old, char* New)
891 //user_hash::iterator newnick;
892 user_hash::iterator oldnick = clientlist.find(Old);
894 log(DEBUG,"ReHashNick: %s %s",Old,New);
896 if (!strcasecmp(Old,New))
898 log(DEBUG,"old nick is new nick, skipping");
899 return oldnick->second;
902 if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
904 log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
906 userrec* olduser = oldnick->second;
907 clientlist[New] = olduser;
908 clientlist.erase(oldnick);
910 log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
912 return clientlist[New];
915 /* adds or updates an entry in the whowas list */
916 void AddWhoWas(userrec* u)
918 whowas_hash::iterator iter = whowas.find(u->nick);
919 WhoWasUser *a = new WhoWasUser();
920 strlcpy(a->nick,u->nick,NICKMAX);
921 strlcpy(a->ident,u->ident,IDENTMAX);
922 strlcpy(a->dhost,u->dhost,160);
923 strlcpy(a->host,u->host,160);
924 strlcpy(a->fullname,u->fullname,MAXGECOS);
925 strlcpy(a->server,u->server,256);
926 a->signon = u->signon;
928 /* MAX_WHOWAS: max number of /WHOWAS items
929 * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
930 * can be replaced by a newer one
933 if (iter == whowas.end())
935 if (whowas.size() >= (unsigned)WHOWAS_MAX)
937 for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
939 // 3600 seconds in an hour ;)
940 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
942 // delete the old one
943 if (i->second) delete i->second;
944 // replace with new one
946 log(DEBUG,"added WHOWAS entry, purged an old record");
950 // no space left and user doesnt exist. Don't leave ram in use!
951 log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
956 log(DEBUG,"added fresh WHOWAS entry");
962 log(DEBUG,"updated WHOWAS entry");
963 if (iter->second) delete iter->second;
969 void* dns_task(void* arg)
971 userrec* u = (userrec*)arg;
972 log(DEBUG,"DNS thread for user %s",u->nick);
977 if (dns1.ReverseLookup(u->ip))
979 log(DEBUG,"DNS Step 1");
980 while (!dns1.HasResult())
984 host = dns1.GetResult();
987 log(DEBUG,"DNS Step 2: '%s'",host.c_str());
988 if (dns2.ForwardLookup(host))
990 while (!dns2.HasResult())
994 ip = dns2.GetResultIP();
995 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
996 if (ip == std::string(u->ip))
998 log(DEBUG,"DNS Step 4");
999 if (host.length() < 160)
1001 log(DEBUG,"DNS Step 5");
1002 strcpy(u->host,host.c_str());
1003 strcpy(u->dhost,host.c_str());
1014 /* add a client connection to the sockets list */
1015 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1019 user_hash::iterator iter;
1021 tempnick = ConvToStr(socket) + "-unknown";
1022 sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1024 iter = clientlist.find(tempnick);
1027 // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1028 // using one as a registered connection. As theyre per fd, we can also safely assume
1029 // that we wont have collisions. Therefore, if the nick exists in the list, its only
1030 // used by a dead socket, erase the iterator so that the new client may reclaim it.
1031 // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1032 // issue in earlier alphas/betas
1033 if (iter != clientlist.end())
1035 userrec* goner = iter->second;
1037 clientlist.erase(iter);
1041 * It is OK to access the value here this way since we know
1042 * it exists, we just created it above.
1044 * At NO other time should you access a value in a map or a
1045 * hash_map this way.
1047 clientlist[tempnick] = new userrec();
1049 NonBlocking(socket);
1050 log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1052 clientlist[tempnick]->fd = socket;
1053 strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1054 strlcpy(clientlist[tempnick]->host, host,160);
1055 strlcpy(clientlist[tempnick]->dhost, host,160);
1056 clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
1057 strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1058 clientlist[tempnick]->registered = 0;
1059 clientlist[tempnick]->signon = TIME + Config->dns_timeout;
1060 clientlist[tempnick]->lastping = 1;
1061 clientlist[tempnick]->port = port;
1062 strlcpy(clientlist[tempnick]->ip,ip,16);
1064 // set the registration timeout for this user
1065 unsigned long class_regtimeout = 90;
1066 int class_flood = 0;
1067 long class_threshold = 5;
1068 long class_sqmax = 262144; // 256kb
1069 long class_rqmax = 4096; // 4k
1071 for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
1073 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1075 class_regtimeout = (unsigned long)i->registration_timeout;
1076 class_flood = i->flood;
1077 clientlist[tempnick]->pingmax = i->pingtime;
1078 class_threshold = i->threshold;
1079 class_sqmax = i->sendqmax;
1080 class_rqmax = i->recvqmax;
1085 clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
1086 clientlist[tempnick]->timeout = TIME+class_regtimeout;
1087 clientlist[tempnick]->flood = class_flood;
1088 clientlist[tempnick]->threshold = class_threshold;
1089 clientlist[tempnick]->sendqmax = class_sqmax;
1090 clientlist[tempnick]->recvqmax = class_rqmax;
1095 for (int i = 0; i < MAXCHANS; i++)
1096 clientlist[tempnick]->chans.push_back(a);
1098 if (clientlist.size() > Config->SoftLimit)
1100 kill_link(clientlist[tempnick],"No more connections allowed");
1104 if (clientlist.size() >= MAXCLIENTS)
1106 kill_link(clientlist[tempnick],"No more connections allowed");
1110 // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1111 // its a pretty big but for the moment valid assumption:
1112 // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1113 // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1114 // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1115 // which for the time being is a physical impossibility (even the largest networks dont have more
1116 // than about 10,000 users on ONE server!)
1117 if ((unsigned)socket > 65534)
1119 kill_link(clientlist[tempnick],"Server is full");
1124 char* e = matches_exception(ip);
1127 char* r = matches_zline(ip);
1130 char reason[MAXBUF];
1131 snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1132 kill_link(clientlist[tempnick],reason);
1136 fd_ref_table[socket] = clientlist[tempnick];
1137 SE->AddFd(socket,true,X_ESTAB_CLIENT);
1140 /* shows the message of the day, and any other on-logon stuff */
1141 void FullConnectUser(userrec* user)
1143 stats->statsConnects++;
1144 user->idle_lastmsg = TIME;
1145 log(DEBUG,"ConnectUser: %s",user->nick);
1147 if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1149 kill_link(user,"Invalid password");
1154 kill_link(user,"Unauthorised connection");
1158 char match_against[MAXBUF];
1159 snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1160 char* e = matches_exception(match_against);
1163 char* r = matches_gline(match_against);
1166 char reason[MAXBUF];
1167 snprintf(reason,MAXBUF,"G-Lined: %s",r);
1168 kill_link_silent(user,reason);
1171 r = matches_kline(user->host);
1174 char reason[MAXBUF];
1175 snprintf(reason,MAXBUF,"K-Lined: %s",r);
1176 kill_link_silent(user,reason);
1182 WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1183 WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
1184 WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1185 WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1186 WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
1187 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1188 std::stringstream v;
1189 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1190 v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1191 v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1192 v << Config->Network;
1193 std::string data005 = v.str();
1194 FOREACH_MOD On005Numeric(data005);
1195 // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1196 // so i'd better split it :)
1197 std::stringstream out(data005);
1198 std::string token = "";
1199 std::string line5 = "";
1200 int token_counter = 0;
1204 line5 = line5 + token + " ";
1206 if ((token_counter >= 13) || (out.eof() == true))
1208 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1215 // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1216 // onto the network and produce 'fake direction'
1217 FOREACH_MOD OnUserConnect(user);
1218 FOREACH_MOD OnGlobalConnect(user);
1219 user->registered = 7;
1220 WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1224 /* shows the message of the day, and any other on-logon stuff */
1225 void ConnectUser(userrec *user)
1227 // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1228 if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1230 FullConnectUser(user);
1234 std::string GetVersionString()
1236 char versiondata[MAXBUF];
1238 char dnsengine[] = "multithread";
1240 char dnsengine[] = "singlethread";
1242 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);
1246 void handle_version(char **parameters, int pcnt, userrec *user)
1248 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1252 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1254 for (unsigned int i = 0; i < cmdlist.size(); i++)
1256 if (!strcasecmp(cmdlist[i].command,commandname))
1258 if (cmdlist[i].handler_function)
1260 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1262 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1264 if (cmdlist[i].flags_needed)
1266 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1284 // calls a handler function for a command
1286 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1288 for (unsigned int i = 0; i < cmdlist.size(); i++)
1290 if (!strcasecmp(cmdlist[i].command,commandname))
1292 if (cmdlist[i].handler_function)
1294 if (pcnt>=cmdlist[i].min_params)
1296 if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1298 if (cmdlist[i].flags_needed)
1300 if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1302 cmdlist[i].handler_function(parameters,pcnt,user);
1307 cmdlist[i].handler_function(parameters,pcnt,user);
1317 void force_nickchange(userrec* user,const char* newnick)
1324 FOREACH_RESULT(OnUserPreNick(user,newnick));
1326 stats->statsCollisions++;
1327 kill_link(user,"Nickname collision");
1330 if (matches_qline(newnick))
1332 stats->statsCollisions++;
1333 kill_link(user,"Nickname collision");
1341 strncpy(nick,newnick,MAXBUF);
1343 if (user->registered == 7)
1347 handle_nick(pars,1,user);
1353 int process_parameters(char **command_p,char *parameters)
1356 int q = strlen(parameters);
1359 /* no parameters, command_p invalid! */
1362 if (parameters[0] == ':')
1364 command_p[0] = parameters+1;
1369 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1371 /* only one parameter */
1372 command_p[0] = parameters;
1373 if (parameters[0] == ':')
1375 if (strchr(parameters,' ') != NULL)
1383 command_p[j++] = parameters;
1384 for (int i = 0; i <= q; i++)
1386 if (parameters[i] == ' ')
1388 command_p[j++] = parameters+i+1;
1389 parameters[i] = '\0';
1390 if (command_p[j-1][0] == ':')
1392 *command_p[j-1]++; /* remove dodgy ":" */
1394 /* parameter like this marks end of the sequence */
1398 return j; /* returns total number of items in the list */
1401 void process_command(userrec *user, char* cmd)
1405 char *command_p[127];
1406 char p[MAXBUF], temp[MAXBUF];
1407 int j, items, cmd_found;
1409 for (int i = 0; i < 127; i++)
1410 command_p[i] = NULL;
1425 int total_params = 0;
1428 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1430 if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1433 // found a 'trailing', we dont count them after this.
1441 // another phidjit bug...
1442 if (total_params > 126)
1444 *(strchr(cmd,' ')) = '\0';
1445 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1449 strlcpy(temp,cmd,MAXBUF);
1451 std::string tmp = cmd;
1452 for (int i = 0; i <= MODCOUNT; i++)
1454 std::string oldtmp = tmp;
1455 modules[i]->OnServerRaw(tmp,true,user);
1458 log(DEBUG,"A Module changed the input string!");
1459 log(DEBUG,"New string: %s",tmp.c_str());
1460 log(DEBUG,"Old string: %s",oldtmp.c_str());
1464 strlcpy(cmd,tmp.c_str(),MAXBUF);
1465 strlcpy(temp,cmd,MAXBUF);
1467 if (!strchr(cmd,' '))
1469 /* no parameters, lets skip the formalities and not chop up
1471 log(DEBUG,"About to preprocess command with no params");
1473 command_p[0] = NULL;
1475 for (unsigned int i = 0; i <= strlen(cmd); i++)
1477 cmd[i] = toupper(cmd[i]);
1485 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1486 for (unsigned int i = 0; i < strlen(temp); i++)
1488 if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1494 /* split the full string into a command plus parameters */
1498 if (strchr(cmd,' '))
1500 for (unsigned int i = 0; i <= strlen(cmd); i++)
1502 /* capitalise the command ONLY, leave params intact */
1503 cmd[i] = toupper(cmd[i]);
1504 /* are we nearly there yet?! :P */
1508 parameters = cmd+i+1;
1516 for (unsigned int i = 0; i <= strlen(cmd); i++)
1518 cmd[i] = toupper(cmd[i]);
1525 if (strlen(command)>MAXCOMMAND)
1527 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1531 for (unsigned int x = 0; x < strlen(command); x++)
1533 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1535 if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1537 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1539 stats->statsUnknown++;
1540 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1547 for (unsigned int i = 0; i != cmdlist.size(); i++)
1549 if (cmdlist[i].command[0])
1551 if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1557 items = process_parameters(command_p,parameters);
1562 command_p[0] = NULL;
1568 command_p[0] = NULL;
1573 /* activity resets the ping pending timer */
1574 user->nping = TIME + user->pingmax;
1575 if ((items) < cmdlist[i].min_params)
1577 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1578 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1581 if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1583 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1584 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1588 if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1590 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1591 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1595 /* if the command isnt USER, PASS, or NICK, and nick is empty,
1597 if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1599 if ((!isnick(user->nick)) || (user->registered != 7))
1601 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1602 WriteServ(user->fd,"451 %s :You have not registered",command);
1606 if ((user->registered == 7) && (!strchr(user->modes,'o')))
1608 std::stringstream dcmds(Config->DisabledCommands);
1609 while (!dcmds.eof())
1611 std::string thiscmd;
1613 if (!strcasecmp(thiscmd.c_str(),command))
1615 // command is disabled!
1616 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1621 if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1623 if (cmdlist[i].handler_function)
1626 /* ikky /stats counters */
1629 cmdlist[i].use_count++;
1630 cmdlist[i].total_bytes+=strlen(temp);
1634 FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1635 if (MOD_RESULT == 1) {
1639 /* WARNING: nothing may come after the
1640 * command handler call, as the handler
1641 * may free the user structure! */
1643 cmdlist[i].handler_function(command_p,items,user);
1649 WriteServ(user->fd,"451 %s :You have not registered",command);
1657 if ((!cmd_found) && (user))
1659 stats->statsUnknown++;
1660 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1664 bool removecommands(const char* source)
1666 bool go_again = true;
1670 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1672 if (!strcmp(i->source,source))
1674 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1685 void process_buffer(const char* cmdbuf,userrec *user)
1689 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1695 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1702 while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1704 strlcpy(cmd,cmdbuf,MAXBUF);
1709 int sl = strlen(cmd)-1;
1710 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1715 if ((cmd[sl] == 13) || (cmd[sl] == 10))
1720 while (cmd[sl] == ' ') // strip trailing spaces
1730 log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
1732 if ((user) && (cmd))
1734 process_command(user,cmd);
1738 char MODERR[MAXBUF];
1745 void erase_factory(int j)
1748 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
1753 factory.push_back(NULL);
1760 void erase_module(int j)
1763 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
1769 modules.push_back(NULL);
1775 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
1779 Config->module_names.erase(v);
1787 bool UnloadModule(const char* filename)
1789 std::string filename_str = filename;
1790 for (unsigned int j = 0; j != Config->module_names.size(); j++)
1792 if (Config->module_names[j] == filename_str)
1794 if (modules[j]->GetVersion().Flags & VF_STATIC)
1796 log(DEFAULT,"Failed to unload STATIC module %s",filename);
1797 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
1800 /* Give the module a chance to tidy out all its metadata */
1801 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1803 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
1805 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1807 modules[j]->OnCleanup(TYPE_USER,u->second);
1809 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
1811 log(DEBUG,"Deleting module...");
1813 log(DEBUG,"Erasing module entry...");
1815 log(DEBUG,"Removing dependent commands...");
1816 removecommands(filename);
1817 log(DEFAULT,"Module %s unloaded",filename);
1822 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
1823 snprintf(MODERR,MAXBUF,"Module not loaded");
1827 bool LoadModule(const char* filename)
1829 char modfile[MAXBUF];
1831 snprintf(modfile,MAXBUF,"%s",filename);
1833 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
1835 std::string filename_str = filename;
1837 if (!DirValid(modfile))
1839 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
1840 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
1844 log(DEBUG,"Loading module: %s",modfile);
1846 if (FileExists(modfile))
1849 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1851 if (Config->module_names[j] == filename_str)
1853 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
1854 snprintf(MODERR,MAXBUF,"Module already loaded");
1858 ircd_module* a = new ircd_module(modfile);
1859 factory[MODCOUNT+1] = a;
1860 if (factory[MODCOUNT+1]->LastError())
1862 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
1863 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
1867 if (factory[MODCOUNT+1]->factory)
1869 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
1870 modules[MODCOUNT+1] = m;
1871 /* save the module and the module's classfactory, if
1872 * this isnt done, random crashes can occur :/ */
1873 Config->module_names.push_back(filename);
1877 log(DEFAULT,"Unable to load %s",modfile);
1878 snprintf(MODERR,MAXBUF,"Factory function failed!");
1885 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1886 snprintf(MODERR,MAXBUF,"Module file could not be found");
1891 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
1897 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1898 int clientportcount = 0;
1899 for (int count = 0; count < ConfValueEnum("bind",&Config->config_f); count++)
1901 ConfValue("bind","port",count,configToken,&Config->config_f);
1902 ConfValue("bind","address",count,Addr,&Config->config_f);
1903 ConfValue("bind","type",count,Type,&Config->config_f);
1904 if (strcmp(Type,"servers"))
1906 // modules handle server bind types now,
1907 // its not a typo in the strcmp.
1908 ports[clientportcount] = atoi(configToken);
1909 strlcpy(Config->addrs[clientportcount],Addr,256);
1911 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1914 portCount = clientportcount;
1916 for (int count = 0; count < portCount; count++)
1918 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
1920 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
1923 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],Config->addrs[count]) == ERROR)
1925 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
1927 else /* well we at least bound to one socket so we'll continue */
1933 /* if we didn't bind to anything then abort */
1934 if (!boundPortCount)
1936 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1937 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
1941 return boundPortCount;
1944 int InspIRCd(char** argv, int argc)
1946 bool expire_run = false;
1947 std::vector<int> activefds;
1951 InspSocket* s = NULL;
1952 InspSocket* s_del = NULL;
1954 unsigned int numberactive;
1955 sockaddr_in sock_us; // our port number
1956 socklen_t uslen; // length of our port number
1958 /* Beta 7 moved all this stuff out of the main function
1959 * into smaller sub-functions, much tidier -- Brain
1961 OpenLog(argv, argc);
1962 Config->ClearStack();
1963 Config->Read(true,NULL);
1965 SetupCommandTable();
1966 AddServerName(Config->ServerName);
1968 boundPortCount = BindPorts();
1971 startup_time = time(NULL);
1973 if (!Config->nofork)
1975 if (DaemonSeed() == ERROR)
1977 printf("ERROR: could not go into daemon mode. Shutting down.\n");
1982 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
1983 * initialize the socket engine.
1985 SE = new SocketEngine();
1987 /* We must load the modules AFTER initializing the socket engine, now */
1990 printf("\nInspIRCd is now running!\n");
1991 if (!Config->nofork)
1993 freopen("/dev/null","w",stdout);
1994 freopen("/dev/null","w",stderr);
1997 /* Add the listening sockets used for client inbound connections
1998 * to the socket engine
2000 for (int count = 0; count < portCount; count++)
2001 SE->AddFd(openSockfd[count],true,X_LISTEN);
2003 WritePID(Config->PID);
2005 /* main loop, this never returns */
2008 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2009 * Once per loop iteration is pleanty.
2014 /* Run background module timers every few seconds
2015 * (the docs say modules shouldnt rely on accurate
2016 * timing using this event, so we dont have to
2017 * time this exactly).
2019 if (((TIME % 8) == 0) && (!expire_run))
2022 FOREACH_MOD OnBackgroundTimer(TIME);
2026 if ((TIME % 8) == 1)
2029 /* Once a second, do the background processing */
2030 if (TIME != OLDTIME)
2031 while (DoBackgroundUserStuff(TIME));
2033 /* Call the socket engine to wait on the active
2034 * file descriptors. The socket engine has everything's
2035 * descriptors in its list... dns, modules, users,
2036 * servers... so its nice and easy, just one call.
2038 SE->Wait(activefds);
2041 * Now process each of the fd's. For users, we have a fast
2042 * lookup table which can find a user by file descriptor, so
2043 * processing them by fd isnt expensive. If we have a lot of
2044 * listening ports or module sockets though, things could get
2047 numberactive = activefds.size();
2048 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2050 int socket_type = SE->GetType(activefds[activefd]);
2051 switch (socket_type)
2053 case X_ESTAB_CLIENT:
2055 cu = fd_ref_table[activefds[activefd]];
2061 case X_ESTAB_MODULE:
2063 /* Process module-owned sockets.
2064 * Modules are encouraged to inherit their sockets from
2065 * InspSocket so we can process them neatly like this.
2067 s = socket_ref[activefds[activefd]];
2069 if ((s) && (!s->Poll()))
2071 log(DEBUG,"Socket poll returned false, close and bail");
2072 SE->DelFd(s->GetFd());
2073 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2075 s_del = (InspSocket*)*a;
2076 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2078 module_sockets.erase(a);
2090 /* When we are using single-threaded dns,
2091 * the sockets for dns end up in our mainloop.
2092 * When we are using multi-threaded dns,
2093 * each thread has its own basic poll() loop
2094 * within it, making them 'fire and forget'
2095 * and independent of the mainloop.
2097 #ifndef THREADED_DNS
2098 dns_poll(activefds[activefd]);
2104 /* It's a listener */
2105 uslen = sizeof(sock_us);
2106 length = sizeof(client);
2107 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
2108 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
2110 in_port = ntohs(sock_us.sin_port);
2111 log(DEBUG,"Accepted socket %d",incomingSockfd);
2112 target = (char*)inet_ntoa(client.sin_addr);
2113 /* Years and years ago, we used to resolve here
2114 * using gethostbyaddr(). That is sucky and we
2115 * don't do that any more...
2117 if (incomingSockfd >= 0)
2119 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
2120 stats->statsAccept++;
2121 AddClient(incomingSockfd, target, in_port, false, target);
2122 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
2126 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
2127 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
2128 stats->statsRefused++;
2133 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
2134 shutdown(incomingSockfd,2);
2135 close(incomingSockfd);
2140 /* Something went wrong if we're in here.
2141 * In fact, so wrong, im not quite sure
2142 * what we would do, so for now, its going
2143 * to safely do bugger all.
2150 /* This is never reached -- we hope! */