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 * ---------------------------------------------------
15 #include "configreader.h"
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 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 sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr) : ServerInstance(Instance), desc("plaintext")
42 Instance->Log(DEBUG,"CRAP");
43 if (!Instance->BindSocket(this->fd,client,server,port,addr))
47 ListenSocket::~ListenSocket()
49 if (this->GetFd() > -1)
51 shutdown(this->fd, 2);
57 void ListenSocket::HandleEvent(EventType et, int errornum)
59 insp_sockaddr sock_us; // our port number
60 socklen_t uslen; // length of our port number
63 int incomingSockfd, in_port;
64 uslen = sizeof(sock_us);
65 length = sizeof(client);
66 incomingSockfd = accept (this->GetFd(),(struct sockaddr*)&client, &length);
68 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, (sockaddr*)&sock_us, &uslen)))
71 in_port = ntohs(sock_us.sin6_port);
73 in_port = ntohs(sock_us.sin_port);
75 NonBlocking(incomingSockfd);
76 if (ServerInstance->Config->GetIOHook(in_port))
81 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
83 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
86 catch (CoreException& modexcept)
88 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
91 ServerInstance->stats->statsAccept++;
93 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin6_addr);
95 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin_addr);
100 shutdown(incomingSockfd,2);
101 close(incomingSockfd);
102 ServerInstance->stats->statsRefused++;
106 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
107 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
109 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
110 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
112 /* First compare the whole bytes, if they dont match, return false */
113 if (memcmp(address, mask, divisor))
116 /* Now if there are any remainder bits, we compare them with logic AND */
118 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
119 /* If they dont match, return false */
122 /* The address matches the mask, to mask_bits bits of mask */
126 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
127 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
129 return MatchCIDR(address, cidr_mask, false);
132 /* 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
133 * If you have a lot of hosts to match, youre probably better off building your mask once
134 * and then using the lower level MatchCIDRBits directly.
136 * This will also attempt to match any leading usernames or nicknames on the mask, using
137 * match(), when match_with_username is true.
139 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
141 unsigned char addr_raw[16];
142 unsigned char mask_raw[16];
143 unsigned int bits = 0;
146 /* The caller is trying to match ident@<mask>/bits.
147 * Chop off the ident@ portion, use match() on it
150 if (match_with_username)
152 /* Duplicate the strings, and try to find the position
153 * of the @ symbol in each */
154 char* address_dupe = strdup(address);
155 char* cidr_dupe = strdup(cidr_mask);
157 /* Use strchr not strrchr, because its going to be nearer to the left */
158 char* username_mask_pos = strrchr(cidr_dupe, '@');
159 char* username_addr_pos = strrchr(address_dupe, '@');
161 /* Both strings have an @ symbol in them */
162 if (username_mask_pos && username_addr_pos)
164 /* Zero out the location of the @ symbol */
165 *username_mask_pos = *username_addr_pos = 0;
167 /* Try and match() the strings before the @
168 * symbols, and recursively call MatchCIDR without
169 * username matching enabled to match the host part.
171 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
173 /* Free the stuff we created */
177 /* Return a result */
182 /* One or both didnt have an @ in,
187 mask = strdup(cidr_mask);
192 /* Make a copy of the cidr mask string,
193 * we're going to change it
195 mask = strdup(cidr_mask);
202 /* Use strrchr for this, its nearer to the right */
203 char* bits_chars = strrchr(mask,'/');
207 bits = atoi(bits_chars + 1);
212 /* No 'number of bits' field! */
217 #ifdef SUPPORT_IP6LINKS
218 in6_addr address_in6;
221 if (inet_pton(AF_INET6, address, &address_in6) > 0)
223 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
225 memcpy(&addr_raw, &address_in6.s6_addr, 16);
226 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
233 /* The address was valid ipv6, but the mask
234 * that goes with it wasnt.
242 if (inet_pton(AF_INET, address, &address_in4) > 0)
244 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
246 memcpy(&addr_raw, &address_in4.s_addr, 4);
247 memcpy(&mask_raw, &mask_in4.s_addr, 4);
254 /* The address was valid ipv4,
255 * but the mask that went with it wasnt.
263 /* The address was neither ipv4 or ipv6 */
268 /* Low-level-match the bits in the raw data */
270 return MatchCIDRBits(addr_raw, mask_raw, bits);
273 void irc::sockets::Blocking(int s)
275 int flags = fcntl(s, F_GETFL, 0);
276 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
279 void irc::sockets::NonBlocking(int s)
281 int flags = fcntl(s, F_GETFL, 0);
282 fcntl(s, F_SETFL, flags | O_NONBLOCK);
285 /** This will bind a socket to a port. It works for UDP/TCP.
286 * It can only bind to IP addresses, if you wish to bind to hostnames
287 * you should first resolve them using class 'Resolver'.
289 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr clientn, insp_sockaddr servern, int port, char* addr)
291 /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
292 sockaddr* server = new sockaddr[2];
293 memset(server,0,sizeof(sockaddr)*2);
303 printf("Address %s not empty\n", addr);
304 /* There is an address here. Is it ipv6? */
305 if (strchr(addr,':'))
307 printf("Address %s is ipv6\n", addr);
310 if (inet_pton(AF_INET6, addr, &addy) < 1)
312 printf("Failed to interpret address %s", addr);
317 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
318 memcpy(&(((sockaddr_in6*)server)->sin6_addr), &addy, sizeof(in6_addr));
319 ((sockaddr_in6*)server)->sin6_port = htons(port);
320 size = sizeof(sockaddr_in6);
325 printf("Address %s is ipv4\n", addr);
327 if (inet_pton(AF_INET, addr, &addy) < 1)
333 ((sockaddr_in*)server)->sin_family = AF_INET;
334 ((sockaddr_in*)server)->sin_addr = addy;
335 ((sockaddr_in*)server)->sin_port = htons(port);
336 size = sizeof(sockaddr_in);
341 printf("Address empty\n");
342 /* Theres no address here, default to ipv6 bind to all */
343 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
344 memset(&(((sockaddr_in6*)server)->sin6_addr), 0, sizeof(in6_addr));
345 ((sockaddr_in6*)server)->sin6_port = htons(port);
346 size = sizeof(sockaddr_in6);
349 /* If we aren't built with ipv6, the choice becomes simple */
350 ((sockaddr_in*)server)->sin_family = AF_INET;
353 /* There is an address here. */
355 if (inet_pton(AF_INET, addr, &addy) < 1)
360 ((sockaddr_in*)server)->sin_addr = addy;
364 /* Bind ipv4 to all */
365 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
367 /* Bind ipv4 port number */
368 ((sockaddr_in*)server)->sin_port = htons(port);
369 size = sizeof(sockaddr_in);
371 ret = bind(sockfd, server, size);
376 Log(DEBUG,"Bind fails it! %s", strerror(errno));
381 if (listen(sockfd, Config->MaxConn) == -1)
383 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
396 int irc::sockets::OpenTCPSocket(char* addr)
400 struct linger linger = { 0 };
402 printf("IPV6 ENABLED OPENTCPSOCKET\n");
403 if (strchr(addr,':') || (!*addr))
405 printf("IPV6 OPENTCPSOCKET DO\n");
406 sockfd = socket (PF_INET6, SOCK_STREAM, 0);
410 printf("IPV6->IPV4 OPENTCPSOCKET DO\n");
411 sockfd = socket (PF_INET, SOCK_STREAM, 0);
415 if ((sockfd = socket (PF_INET, SOCK_STREAM, 0)) < 0)
418 printf("SOCKET FAIL: %s\n", strerror(errno));
423 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
424 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
427 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
432 /* XXX: Probably belongs in class InspIRCd */
433 bool InspIRCd::HasPort(int port, char* addr)
435 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
437 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
445 /* XXX: Probably belongs in class InspIRCd */
446 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
448 Log(DEBUG,"BINDING PORTS");
449 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
450 insp_sockaddr client, server;
451 int clientportcount = 0;
452 int BoundPortCount = 0;
456 int InitialPortCount = stats->BoundPortCount;
458 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
460 Log(DEBUG,"FOUND PORT");
461 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
462 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
463 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
465 if ((!*Type) || (!strcmp(Type,"clients")))
467 irc::portparser portrange(configToken, false);
469 while ((portno = portrange.GetToken()))
471 if (!HasPort(portno, Addr))
474 Config->ports[clientportcount+InitialPortCount] = portno;
478 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
486 int PortCount = clientportcount;
489 BoundPortCount = stats->BoundPortCount;
490 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
492 int fd = OpenTCPSocket(Config->addrs[count]);
495 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
496 Log(DEBUG,"SOCKET FAIL");
501 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
502 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
504 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
506 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
507 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
508 close(Config->openSockfd[BoundPortCount]->GetFd());
509 delete Config->openSockfd[BoundPortCount];
510 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
517 return InitialPortCount + BoundPortCount;
519 return InitialPortCount;
523 int PortCount = clientportcount;
525 for (int count = 0; count < PortCount; count++)
527 int fd = OpenTCPSocket(Config->addrs[count]);
530 Log(DEBUG,"SOCKET FAIL");
531 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
536 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
537 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
542 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
545 return BoundPortCount;
548 const char* irc::sockets::insp_ntoa(insp_inaddr n)
550 static char buf[1024];
551 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
555 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
557 return inet_pton(AF_FAMILY, a, n);