1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
16 #include "socketengine.h"
19 using namespace irc::sockets;
21 /* Used when comparing CIDR masks for the modulus bits left over.
22 * A lot of ircd's seem to do this:
23 * ((-1) << (8 - (mask % 8)))
24 * But imho, it sucks in comparison to a nice neat lookup table.
26 const unsigned char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
27 0x80, /* 10000000 - 1 bits */
28 0xC0, /* 11000000 - 2 bits */
29 0xE0, /* 11100000 - 3 bits */
30 0xF0, /* 11110000 - 4 bits */
31 0xF8, /* 11111000 - 5 bits */
32 0xFC, /* 11111100 - 6 bits */
33 0xFE /* 11111110 - 7 bits */
37 ListenSocket::ListenSocket(InspIRCd* Instance, int port, char* addr) : ServerInstance(Instance), desc("plaintext"), bind_addr(addr), bind_port(port)
39 this->SetFd(OpenTCPSocket(addr));
40 if (this->GetFd() > -1)
42 if (!Instance->BindSocket(this->fd,port,addr))
45 if ((!*addr) || (strchr(addr,':')))
46 this->family = AF_INET6;
49 this->family = AF_INET;
50 Instance->SE->AddFd(this);
54 ListenSocket::~ListenSocket()
56 if (this->GetFd() > -1)
58 ServerInstance->SE->DelFd(this);
59 ServerInstance->Log(DEBUG,"Shut down listener on fd %d", this->fd);
60 if (ServerInstance->SE->Shutdown(this, 2) || ServerInstance->SE->Close(this))
61 ServerInstance->Log(DEBUG,"Failed to cancel listener: %s", strerror(errno));
66 void ListenSocket::HandleEvent(EventType et, int errornum)
68 sockaddr* sock_us = new sockaddr[2]; // our port number
69 sockaddr* client = new sockaddr[2];
70 socklen_t uslen, length; // length of our port number
71 int incomingSockfd, in_port;
74 if (this->family == AF_INET6)
76 uslen = sizeof(sockaddr_in6);
77 length = sizeof(sockaddr_in6);
82 uslen = sizeof(sockaddr_in);
83 length = sizeof(sockaddr_in);
86 incomingSockfd = ServerInstance->SE->Accept(this, (sockaddr*)client, &length);
88 if ((incomingSockfd > -1) && (!ServerInstance->SE->GetSockName(this, sock_us, &uslen)))
92 if (this->family == AF_INET6)
94 inet_ntop(AF_INET6, &((const sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
95 in_port = ntohs(((sockaddr_in6*)sock_us)->sin6_port);
100 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
101 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
104 ServerInstance->SE->NonBlocking(incomingSockfd);
106 if (ServerInstance->Config->GetIOHook(in_port))
110 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, buf, in_port);
112 catch (CoreException& modexcept)
114 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
117 ServerInstance->stats->statsAccept++;
118 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, this->family, client);
122 ServerInstance->SE->Shutdown(incomingSockfd, 2);
123 close(incomingSockfd);
124 ServerInstance->stats->statsRefused++;
130 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
131 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
133 unsigned int divisor = mask_bits / 8; /* Number of whole bytes in the mask */
134 unsigned int modulus = mask_bits % 8; /* Remaining bits in the mask after whole bytes are dealt with */
136 /* First (this is faster) compare the odd bits with logic ops */
138 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
139 /* If they dont match, return false */
142 /* Secondly (this is slower) compare the whole bytes */
143 if (memcmp(address, mask, divisor))
146 /* The address matches the mask, to mask_bits bits of mask */
150 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
151 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
153 return MatchCIDR(address, cidr_mask, false);
156 /* 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
157 * If you have a lot of hosts to match, youre probably better off building your mask once
158 * and then using the lower level MatchCIDRBits directly.
160 * This will also attempt to match any leading usernames or nicknames on the mask, using
161 * match(), when match_with_username is true.
163 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
165 unsigned char addr_raw[16];
166 unsigned char mask_raw[16];
167 unsigned int bits = 0;
170 /* The caller is trying to match ident@<mask>/bits.
171 * Chop off the ident@ portion, use match() on it
174 if (match_with_username)
176 /* Duplicate the strings, and try to find the position
177 * of the @ symbol in each */
178 char* address_dupe = strdup(address);
179 char* cidr_dupe = strdup(cidr_mask);
181 /* Use strchr not strrchr, because its going to be nearer to the left */
182 char* username_mask_pos = strrchr(cidr_dupe, '@');
183 char* username_addr_pos = strrchr(address_dupe, '@');
185 /* Both strings have an @ symbol in them */
186 if (username_mask_pos && username_addr_pos)
188 /* Zero out the location of the @ symbol */
189 *username_mask_pos = *username_addr_pos = 0;
191 /* Try and match() the strings before the @
192 * symbols, and recursively call MatchCIDR without
193 * username matching enabled to match the host part.
195 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
197 /* Free the stuff we created */
201 /* Return a result */
206 /* One or both didnt have an @ in,
211 mask = strdup(cidr_mask);
216 /* Make a copy of the cidr mask string,
217 * we're going to change it
219 mask = strdup(cidr_mask);
226 /* Use strrchr for this, its nearer to the right */
227 char* bits_chars = strrchr(mask,'/');
231 bits = atoi(bits_chars + 1);
236 /* No 'number of bits' field! */
241 #ifdef SUPPORT_IP6LINKS
242 in6_addr address_in6;
245 if (inet_pton(AF_INET6, address, &address_in6) > 0)
247 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
249 memcpy(&addr_raw, &address_in6.s6_addr, 16);
250 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
257 /* The address was valid ipv6, but the mask
258 * that goes with it wasnt.
266 if (inet_pton(AF_INET, address, &address_in4) > 0)
268 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
270 memcpy(&addr_raw, &address_in4.s_addr, 4);
271 memcpy(&mask_raw, &mask_in4.s_addr, 4);
278 /* The address was valid ipv4,
279 * but the mask that went with it wasnt.
287 /* The address was neither ipv4 or ipv6 */
292 /* Low-level-match the bits in the raw data */
294 return MatchCIDRBits(addr_raw, mask_raw, bits);
297 /** This will bind a socket to a port. It works for UDP/TCP.
298 * It can only bind to IP addresses, if you wish to bind to hostnames
299 * you should first resolve them using class 'Resolver'.
301 bool InspIRCd::BindSocket(int sockfd, int port, char* addr, bool dolisten)
303 /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
304 sockaddr* server = new sockaddr[2];
305 memset(server,0,sizeof(sockaddr)*2);
315 /* There is an address here. Is it ipv6? */
316 if (strchr(addr,':'))
320 if (inet_pton(AF_INET6, addr, &addy) < 1)
326 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
327 memcpy(&(((sockaddr_in6*)server)->sin6_addr), &addy, sizeof(in6_addr));
328 ((sockaddr_in6*)server)->sin6_port = htons(port);
329 size = sizeof(sockaddr_in6);
335 if (inet_pton(AF_INET, addr, &addy) < 1)
341 ((sockaddr_in*)server)->sin_family = AF_INET;
342 ((sockaddr_in*)server)->sin_addr = addy;
343 ((sockaddr_in*)server)->sin_port = htons(port);
344 size = sizeof(sockaddr_in);
351 /* Port -1: Means UDP IPV4 port binding - Special case
352 * used by DNS engine.
354 ((sockaddr_in*)server)->sin_family = AF_INET;
355 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
356 ((sockaddr_in*)server)->sin_port = 0;
357 size = sizeof(sockaddr_in);
361 /* Theres no address here, default to ipv6 bind to all */
362 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
363 memset(&(((sockaddr_in6*)server)->sin6_addr), 0, sizeof(in6_addr));
364 ((sockaddr_in6*)server)->sin6_port = htons(port);
365 size = sizeof(sockaddr_in6);
369 /* If we aren't built with ipv6, the choice becomes simple */
370 ((sockaddr_in*)server)->sin_family = AF_INET;
373 /* There is an address here. */
375 if (inet_pton(AF_INET, addr, &addy) < 1)
380 ((sockaddr_in*)server)->sin_addr = addy;
384 /* Bind ipv4 to all */
385 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
387 /* Bind ipv4 port number */
388 ((sockaddr_in*)server)->sin_port = htons(port);
389 size = sizeof(sockaddr_in);
391 ret = SE->Bind(sockfd, server, size);
402 if (SE->Listen(sockfd, Config->MaxConn) == -1)
404 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
409 this->Log(DEBUG,"New socket binding for %d with listen: %s:%d", sockfd, addr, port);
410 SE->NonBlocking(sockfd);
416 this->Log(DEBUG,"New socket binding for %d without listen: %s:%d", sockfd, addr, port);
423 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
427 struct linger linger = { 0 };
429 if (strchr(addr,':') || (!*addr))
430 sockfd = socket (PF_INET6, socktype, 0);
432 sockfd = socket (PF_INET, socktype, 0);
435 if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
442 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
443 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
446 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (char*)&linger,sizeof(linger));
451 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
453 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
455 bool started_with_nothing = (Config->ports.size() == 0);
456 std::vector<std::pair<std::string, int> > old_ports;
458 /* XXX: Make a copy of the old ip/port pairs here */
459 for (std::vector<ListenSocket*>::iterator o = Config->ports.begin(); o != Config->ports.end(); ++o)
460 old_ports.push_back(make_pair((*o)->GetIP(), (*o)->GetPort()));
462 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
464 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
465 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
466 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
468 if ((!*Type) || (!strcmp(Type,"clients")))
470 irc::portparser portrange(configToken, false);
472 while ((portno = portrange.GetToken()))
478 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
480 if (((*n)->GetIP() == Addr) && ((*n)->GetPort() == portno))
483 /* XXX: Here, erase from our copy of the list */
484 for (std::vector<std::pair<std::string, int> >::iterator k = old_ports.begin(); k != old_ports.end(); ++k)
486 if ((k->first == Addr) && (k->second == portno))
496 ListenSocket* ll = new ListenSocket(this, portno, Addr);
497 if (ll->GetFd() > -1)
500 Config->ports.push_back(ll);
504 failed_ports.push_back(std::make_pair(Addr, portno));
512 /* XXX: Here, anything left in our copy list, close as removed */
513 if (!started_with_nothing)
515 for (size_t k = 0; k < old_ports.size(); ++k)
517 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
519 if (((*n)->GetIP() == old_ports[k].first) && ((*n)->GetPort() == old_ports[k].second))
521 this->Log(DEFAULT,"Port binding %s:%d was removed from the config file, closing.", old_ports[k].first.c_str(), old_ports[k].second);
523 Config->ports.erase(n);
533 const char* irc::sockets::insp_ntoa(insp_inaddr n)
535 static char buf[1024];
536 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
540 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
542 return inet_pton(AF_FAMILY, a, n);