1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDsocket */
18 #include "socketengine.h"
21 using namespace irc::sockets;
23 /* Used when comparing CIDR masks for the modulus bits left over.
24 * A lot of ircd's seem to do this:
25 * ((-1) << (8 - (mask % 8)))
26 * But imho, it sucks in comparison to a nice neat lookup table.
28 const unsigned char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
29 0x80, /* 10000000 - 1 bits */
30 0xC0, /* 11000000 - 2 bits */
31 0xE0, /* 11100000 - 3 bits */
32 0xF0, /* 11110000 - 4 bits */
33 0xF8, /* 11111000 - 5 bits */
34 0xFC, /* 11111100 - 6 bits */
35 0xFE /* 11111110 - 7 bits */
39 ListenSocket::ListenSocket(InspIRCd* Instance, int port, char* addr) : ServerInstance(Instance), desc("plaintext"), bind_addr(addr), bind_port(port)
41 this->SetFd(OpenTCPSocket(addr));
42 if (this->GetFd() > -1)
44 if (!Instance->BindSocket(this->fd,port,addr))
47 if ((!*addr) || (strchr(addr,':')))
48 this->family = AF_INET6;
51 this->family = AF_INET;
52 Instance->SE->AddFd(this);
56 ListenSocket::~ListenSocket()
58 if (this->GetFd() > -1)
60 ServerInstance->SE->DelFd(this);
61 ServerInstance->Logs->Log("SOCKET", DEBUG,"Shut down listener on fd %d", this->fd);
62 if (ServerInstance->SE->Shutdown(this, 2) || ServerInstance->SE->Close(this))
63 ServerInstance->Logs->Log("SOCKET", DEBUG,"Failed to cancel listener: %s", strerror(errno));
69 // XXX this is a bit of an untidy way to avoid reallocating this constantly. also, we leak it on shutdown.. but that's kinda minor - w
70 static sockaddr *sock_us;
71 static sockaddr *client;
72 static bool setup_sock = false;
74 void ListenSocket::HandleEvent(EventType, int)
76 socklen_t uslen, length; // length of our port number
77 int incomingSockfd, in_port;
81 sock_us = new sockaddr[2];
82 client = new sockaddr[2];
87 if (this->family == AF_INET6)
89 uslen = sizeof(sockaddr_in6);
90 length = sizeof(sockaddr_in6);
95 uslen = sizeof(sockaddr_in);
96 length = sizeof(sockaddr_in);
99 incomingSockfd = ServerInstance->SE->Accept(this, (sockaddr*)client, &length);
101 if ((incomingSockfd > -1) && (!ServerInstance->SE->GetSockName(this, sock_us, &uslen)))
106 *target = *buf = '\0';
108 sockaddr* raddr = new sockaddr[2];
111 if (this->family == AF_INET6)
113 in_port = ntohs(((sockaddr_in6*)sock_us)->sin6_port);
114 inet_ntop(AF_INET6, &((const sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
115 socklen_t raddrsz = sizeof(sockaddr_in6);
116 if (getpeername(incomingSockfd, (sockaddr*) raddr, &raddrsz) == 0)
117 inet_ntop(AF_INET6, &((const sockaddr_in6*)raddr)->sin6_addr, target, sizeof(target));
119 ServerInstance->Logs->Log("SOCKET", DEBUG, "Can't get peername: %s", strerror(errno));
124 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
125 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
126 socklen_t raddrsz = sizeof(sockaddr_in);
127 if (getpeername(incomingSockfd, (sockaddr*) raddr, &raddrsz) == 0)
128 inet_ntop(AF_INET, &((const sockaddr_in*)raddr)->sin_addr, target, sizeof(target));
130 ServerInstance->Logs->Log("SOCKET", DEBUG, "Can't get peername: %s", strerror(errno));
136 ServerInstance->SE->NonBlocking(incomingSockfd);
138 ServerInstance->stats->statsAccept++;
139 ServerInstance->Users->AddClient(ServerInstance, incomingSockfd, in_port, false, this->family, client, target);
143 ServerInstance->SE->Shutdown(incomingSockfd, 2);
144 ServerInstance->SE->Close(incomingSockfd);
145 ServerInstance->stats->statsRefused++;
149 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
150 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
152 unsigned int divisor = mask_bits / 8; /* Number of whole bytes in the mask */
153 unsigned int modulus = mask_bits % 8; /* Remaining bits in the mask after whole bytes are dealt with */
155 /* First (this is faster) compare the odd bits with logic ops */
157 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
158 /* If they dont match, return false */
161 /* Secondly (this is slower) compare the whole bytes */
162 if (memcmp(address, mask, divisor))
165 /* The address matches the mask, to mask_bits bits of mask */
169 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
170 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
172 return MatchCIDR(address, cidr_mask, false);
175 /* 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
176 * If you have a lot of hosts to match, youre probably better off building your mask once
177 * and then using the lower level MatchCIDRBits directly.
179 * This will also attempt to match any leading usernames or nicknames on the mask, using
180 * match(), when match_with_username is true.
182 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
184 unsigned char addr_raw[16];
185 unsigned char mask_raw[16];
186 unsigned int bits = 0;
189 /* The caller is trying to match ident@<mask>/bits.
190 * Chop off the ident@ portion, use match() on it
193 if (match_with_username)
195 /* Duplicate the strings, and try to find the position
196 * of the @ symbol in each */
197 char* address_dupe = strdup(address);
198 char* cidr_dupe = strdup(cidr_mask);
200 /* Use strchr not strrchr, because its going to be nearer to the left */
201 char* username_mask_pos = strrchr(cidr_dupe, '@');
202 char* username_addr_pos = strrchr(address_dupe, '@');
204 /* Both strings have an @ symbol in them */
205 if (username_mask_pos && username_addr_pos)
207 /* Zero out the location of the @ symbol */
208 *username_mask_pos = *username_addr_pos = 0;
210 /* Try and match() the strings before the @
211 * symbols, and recursively call MatchCIDR without
212 * username matching enabled to match the host part.
214 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
216 /* Free the stuff we created */
220 /* Return a result */
225 /* One or both didnt have an @ in,
230 mask = strdup(cidr_mask);
235 /* Make a copy of the cidr mask string,
236 * we're going to change it
238 mask = strdup(cidr_mask);
245 /* Use strrchr for this, its nearer to the right */
246 char* bits_chars = strrchr(mask,'/');
250 bits = atoi(bits_chars + 1);
255 /* No 'number of bits' field! */
260 #ifdef SUPPORT_IP6LINKS
261 in6_addr address_in6;
264 if (inet_pton(AF_INET6, address, &address_in6) > 0)
266 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
268 memcpy(&addr_raw, &address_in6.s6_addr, 16);
269 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
276 /* The address was valid ipv6, but the mask
277 * that goes with it wasnt.
285 if (inet_pton(AF_INET, address, &address_in4) > 0)
287 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
289 memcpy(&addr_raw, &address_in4.s_addr, 4);
290 memcpy(&mask_raw, &mask_in4.s_addr, 4);
297 /* The address was valid ipv4,
298 * but the mask that went with it wasnt.
306 /* The address was neither ipv4 or ipv6 */
311 /* Low-level-match the bits in the raw data */
313 return MatchCIDRBits(addr_raw, mask_raw, bits);
316 /** This will bind a socket to a port. It works for UDP/TCP.
317 * It can only bind to IP addresses, if you wish to bind to hostnames
318 * you should first resolve them using class 'Resolver'.
320 bool InspIRCd::BindSocket(int sockfd, int port, const char* addr, bool dolisten)
322 /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
323 sockaddr* servaddr = new sockaddr[2];
324 memset(servaddr,0,sizeof(sockaddr)*2);
334 /* There is an address here. Is it ipv6? */
335 if (strchr(addr,':'))
339 if (inet_pton(AF_INET6, addr, &addy) < 1)
345 ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
346 memcpy(&(((sockaddr_in6*)servaddr)->sin6_addr), &addy, sizeof(in6_addr));
347 ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
348 size = sizeof(sockaddr_in6);
354 if (inet_pton(AF_INET, addr, &addy) < 1)
360 ((sockaddr_in*)servaddr)->sin_family = AF_INET;
361 ((sockaddr_in*)servaddr)->sin_addr = addy;
362 ((sockaddr_in*)servaddr)->sin_port = htons(port);
363 size = sizeof(sockaddr_in);
370 /* Port -1: Means UDP IPV4 port binding - Special case
371 * used by DNS engine.
373 ((sockaddr_in*)servaddr)->sin_family = AF_INET;
374 ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
375 ((sockaddr_in*)servaddr)->sin_port = 0;
376 size = sizeof(sockaddr_in);
380 /* Theres no address here, default to ipv6 bind to all */
381 ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
382 memset(&(((sockaddr_in6*)servaddr)->sin6_addr), 0, sizeof(in6_addr));
383 ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
384 size = sizeof(sockaddr_in6);
388 /* If we aren't built with ipv6, the choice becomes simple */
389 ((sockaddr_in*)servaddr)->sin_family = AF_INET;
392 /* There is an address here. */
394 if (inet_pton(AF_INET, addr, &addy) < 1)
399 ((sockaddr_in*)servaddr)->sin_addr = addy;
403 /* Bind ipv4 to all */
404 ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
406 /* Bind ipv4 port number */
407 ((sockaddr_in*)servaddr)->sin_port = htons(port);
408 size = sizeof(sockaddr_in);
410 ret = SE->Bind(sockfd, servaddr, size);
421 if (SE->Listen(sockfd, Config->MaxConn) == -1)
423 this->Logs->Log("SOCKET",DEFAULT,"ERROR in listen(): %s",strerror(errno));
428 this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d with listen: %s:%d", sockfd, addr, port);
429 SE->NonBlocking(sockfd);
435 this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d without listen: %s:%d", sockfd, addr, port);
442 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
447 struct linger linger = { 0, 0 };
449 if (strchr(addr,':') || (!*addr))
450 sockfd = socket (PF_INET6, socktype, 0);
452 sockfd = socket (PF_INET, socktype, 0);
455 if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
462 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
463 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
466 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (char*)&linger,sizeof(linger));
471 int InspIRCd::BindPorts(bool, int &ports_found, FailedPortList &failed_ports)
473 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
475 bool started_with_nothing = (Config->ports.size() == 0);
476 std::vector<std::pair<std::string, int> > old_ports;
478 /* XXX: Make a copy of the old ip/port pairs here */
479 for (std::vector<ListenSocket*>::iterator o = Config->ports.begin(); o != Config->ports.end(); ++o)
480 old_ports.push_back(make_pair((*o)->GetIP(), (*o)->GetPort()));
482 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
484 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
485 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
486 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
488 if (strncmp(Addr, "::ffff:", 7) == 0)
489 this->Logs->Log("SOCKET",DEFAULT, "Using 4in6 (::ffff:) isn't recommended. You should bind IPv4 addresses directly instead.");
491 if ((!*Type) || (!strcmp(Type,"clients")))
493 irc::portparser portrange(configToken, false);
495 while ((portno = portrange.GetToken()))
501 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
503 if (((*n)->GetIP() == Addr) && ((*n)->GetPort() == portno))
506 /* XXX: Here, erase from our copy of the list */
507 for (std::vector<std::pair<std::string, int> >::iterator k = old_ports.begin(); k != old_ports.end(); ++k)
509 if ((k->first == Addr) && (k->second == portno))
519 ListenSocket* ll = new ListenSocket(this, portno, Addr);
520 if (ll->GetFd() > -1)
523 Config->ports.push_back(ll);
527 failed_ports.push_back(std::make_pair(Addr, portno));
535 /* XXX: Here, anything left in our copy list, close as removed */
536 if (!started_with_nothing)
538 for (size_t k = 0; k < old_ports.size(); ++k)
540 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
542 if (((*n)->GetIP() == old_ports[k].first) && ((*n)->GetPort() == old_ports[k].second))
544 this->Logs->Log("SOCKET",DEFAULT,"Port binding %s:%d was removed from the config file, closing.", old_ports[k].first.c_str(), old_ports[k].second);
546 Config->ports.erase(n);
556 const char* irc::sockets::insp_ntoa(insp_inaddr n)
558 static char buf[1024];
559 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
563 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
565 return inet_pton(AF_FAMILY, a, n);