1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 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 "configreader.h"
21 #include "inspstring.h"
22 #include "socketengine.h"
26 using namespace irc::sockets;
28 /* Used when comparing CIDR masks for the modulus bits left over.
29 * A lot of ircd's seem to do this:
30 * ((-1) << (8 - (mask % 8)))
31 * But imho, it sucks in comparison to a nice neat lookup table.
33 const char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
34 0x80, /* 10000000 - 1 bits */
35 0xC0, /* 11000000 - 2 bits */
36 0xE0, /* 11100000 - 3 bits */
37 0xF0, /* 11110000 - 4 bits */
38 0xF8, /* 11111000 - 5 bits */
39 0xFC, /* 11111100 - 6 bits */
40 0xFE /* 11111110 - 7 bits */
44 ListenSocket::ListenSocket(InspIRCd* Instance, int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr) : ServerInstance(Instance)
47 Instance->Log(DEBUG,"Binding to port %s:%d",addr,port);
48 if (!Instance->BindSocket(this->fd,client,server,port,addr))
50 Instance->Log(DEBUG,"Binding failed!");
55 void ListenSocket::HandleEvent(EventType et)
57 insp_sockaddr sock_us; // our port number
58 socklen_t uslen; // length of our port number
61 int incomingSockfd, in_port;
63 ServerInstance->Log(DEBUG,"Handle ListenSocket event");
65 uslen = sizeof(sock_us);
66 length = sizeof(client);
67 incomingSockfd = accept (this->GetFd(),(struct sockaddr*)&client, &length);
69 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, (sockaddr*)&sock_us, &uslen)))
72 in_port = ntohs(sock_us.sin6_port);
74 in_port = ntohs(sock_us.sin_port);
76 ServerInstance->Log(DEBUG,"Accepted socket %d",incomingSockfd);
77 NonBlocking(incomingSockfd);
78 if (ServerInstance->Config->GetIOHook(in_port))
83 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
85 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
88 catch (ModuleException& modexcept)
90 ServerInstance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
93 ServerInstance->stats->statsAccept++;
95 ServerInstance->Log(DEBUG,"Add ipv6 client");
96 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin6_addr);
98 ServerInstance->Log(DEBUG,"Add ipv4 client");
99 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin_addr);
101 ServerInstance->Log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
105 ServerInstance->Log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
106 shutdown(incomingSockfd,2);
107 close(incomingSockfd);
108 ServerInstance->stats->statsRefused++;
112 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
113 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
115 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
116 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
118 /* First compare the whole bytes, if they dont match, return false */
119 if (memcmp(address, mask, divisor))
122 /* Now if there are any remainder bits, we compare them with logic AND */
124 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
125 /* If they dont match, return false */
128 /* The address matches the mask, to mask_bits bits of mask */
132 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
133 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
135 return MatchCIDR(address, cidr_mask, false);
138 /* Match CIDR strings, e.g. 127.0.0.1 to 127.0.0.0/8 or 3ffe:1:5:6::8 to 3ffe:1::0/32
139 * If you have a lot of hosts to match, youre probably better off building your mask once
140 * and then using the lower level MatchCIDRBits directly.
142 * This will also attempt to match any leading usernames or nicknames on the mask, using
143 * match(), when match_with_username is true.
145 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
147 unsigned char addr_raw[16];
148 unsigned char mask_raw[16];
149 unsigned int bits = 0;
152 /* The caller is trying to match ident@<mask>/bits.
153 * Chop off the ident@ portion, use match() on it
156 if (match_with_username)
158 /* Duplicate the strings, and try to find the position
159 * of the @ symbol in each */
160 char* address_dupe = strdup(address);
161 char* cidr_dupe = strdup(cidr_mask);
163 /* Use strchr not strrchr, because its going to be nearer to the left */
164 char* username_mask_pos = strrchr(cidr_dupe, '@');
165 char* username_addr_pos = strrchr(address_dupe, '@');
167 /* Both strings have an @ symbol in them */
168 if (username_mask_pos && username_addr_pos)
170 /* Zero out the location of the @ symbol */
171 *username_mask_pos = *username_addr_pos = 0;
173 /* Try and match() the strings before the @
174 * symbols, and recursively call MatchCIDR without
175 * username matching enabled to match the host part.
177 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
179 /* Free the stuff we created */
183 /* Return a result */
188 /* One or both didnt have an @ in,
193 mask = strdup(cidr_mask);
198 /* Make a copy of the cidr mask string,
199 * we're going to change it
201 mask = strdup(cidr_mask);
208 /* Use strrchr for this, its nearer to the right */
209 char* bits_chars = strrchr(mask,'/');
213 bits = atoi(bits_chars + 1);
218 /* No 'number of bits' field! */
222 #ifdef SUPPORT_IP6LINKS
223 in6_addr address_in6;
226 if (inet_pton(AF_INET6, address, &address_in6) > 0)
228 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
230 memcpy(&addr_raw, &address_in6.s6_addr, 16);
231 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
238 /* The address was valid ipv6, but the mask
239 * that goes with it wasnt.
247 if (inet_pton(AF_INET, address, &address_in4) > 0)
249 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
251 memcpy(&addr_raw, &address_in4.s_addr, 4);
252 memcpy(&mask_raw, &mask_in4.s_addr, 4);
259 /* The address was valid ipv4,
260 * but the mask that went with it wasnt.
268 /* The address was neither ipv4 or ipv6 */
273 /* Low-level-match the bits in the raw data */
275 return MatchCIDRBits(addr_raw, mask_raw, bits);
278 inline void irc::sockets::Blocking(int s)
280 int flags = fcntl(s, F_GETFL, 0);
281 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
284 inline void irc::sockets::NonBlocking(int s)
286 int flags = fcntl(s, F_GETFL, 0);
287 fcntl(s, F_SETFL, flags | O_NONBLOCK);
291 /** This will bind a socket to a port. It works for UDP/TCP.
292 * It can only bind to IP addresses, if you wish to bind to hostnames
293 * you should first resolve them using class 'Resolver'.
295 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
297 memset(&server,0,sizeof(server));
303 if ((*addr) && (insp_aton(addr,&addy) < 1))
305 this->Log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
310 server.sin6_family = AF_FAMILY;
312 server.sin_family = AF_FAMILY;
317 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
319 server.sin_addr.s_addr = htonl(INADDR_ANY);
325 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
327 server.sin_addr = addy;
331 server.sin6_port = htons(port);
333 server.sin_port = htons(port);
335 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
341 this->Log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
342 if (listen(sockfd, Config->MaxConn) == -1)
344 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
357 int irc::sockets::OpenTCPSocket()
361 struct linger linger = { 0 };
363 if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
369 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
370 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
373 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
378 /* XXX: Probably belongs in class InspIRCd */
379 bool InspIRCd::HasPort(int port, char* addr)
381 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
383 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
391 /* XXX: Probably belongs in class InspIRCd */
392 int InspIRCd::BindPorts(bool bail)
394 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
395 insp_sockaddr client, server;
396 int clientportcount = 0;
397 int BoundPortCount = 0;
401 int InitialPortCount = stats->BoundPortCount;
402 this->Log(DEBUG,"Initial port count: %d",InitialPortCount);
404 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
406 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
407 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
408 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
410 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
412 // modules handle server bind types now
413 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
417 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
419 this->Log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
422 int PortCount = clientportcount;
425 BoundPortCount = stats->BoundPortCount;
426 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
428 int fd = OpenTCPSocket();
431 this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
435 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
436 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
438 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
440 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
441 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
442 close(Config->openSockfd[BoundPortCount]->GetFd());
443 delete Config->openSockfd[BoundPortCount];
448 /*if (!BindSocket(Config->openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
450 this->Log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
454 return InitialPortCount + BoundPortCount;
458 this->Log(DEBUG,"There is nothing new to bind!");
460 return InitialPortCount;
463 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
465 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
466 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
467 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
469 if ((!*Type) || (!strcmp(Type,"clients")))
471 // modules handle server bind types now
472 Config->ports[clientportcount] = atoi(configToken);
474 // If the client put bind "*", this is an unrealism.
475 // We don't actually support this as documented, but
476 // i got fed up of people trying it, so now it converts
477 // it to an empty string meaning the same 'bind to all'.
481 strlcpy(Config->addrs[clientportcount],Addr,256);
483 this->Log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
487 int PortCount = clientportcount;
489 for (int count = 0; count < PortCount; count++)
491 int fd = OpenTCPSocket();
494 this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
498 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
499 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
503 /*if (!BindSocket(Config->openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
505 this->Log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
509 return BoundPortCount;
512 const char* irc::sockets::insp_ntoa(insp_inaddr n)
514 static char buf[1024];
515 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
519 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
521 return inet_pton(AF_FAMILY, a, n);