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 if (!Instance->BindSocket(this->fd,client,server,port,addr))
46 ListenSocket::~ListenSocket()
48 if (this->GetFd() > -1)
50 shutdown(this->fd, 2);
56 void ListenSocket::HandleEvent(EventType et, int errornum)
58 insp_sockaddr sock_us; // our port number
59 socklen_t uslen; // length of our port number
62 int incomingSockfd, in_port;
63 uslen = sizeof(sock_us);
64 length = sizeof(client);
65 incomingSockfd = accept (this->GetFd(),(struct sockaddr*)&client, &length);
67 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, (sockaddr*)&sock_us, &uslen)))
70 in_port = ntohs(sock_us.sin6_port);
72 in_port = ntohs(sock_us.sin_port);
74 NonBlocking(incomingSockfd);
75 if (ServerInstance->Config->GetIOHook(in_port))
80 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
82 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
85 catch (CoreException& modexcept)
87 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
90 ServerInstance->stats->statsAccept++;
92 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin6_addr);
94 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin_addr);
99 shutdown(incomingSockfd,2);
100 close(incomingSockfd);
101 ServerInstance->stats->statsRefused++;
105 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
106 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
108 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
109 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
111 /* First compare the whole bytes, if they dont match, return false */
112 if (memcmp(address, mask, divisor))
115 /* Now if there are any remainder bits, we compare them with logic AND */
117 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
118 /* If they dont match, return false */
121 /* The address matches the mask, to mask_bits bits of mask */
125 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
126 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
128 return MatchCIDR(address, cidr_mask, false);
131 /* 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
132 * If you have a lot of hosts to match, youre probably better off building your mask once
133 * and then using the lower level MatchCIDRBits directly.
135 * This will also attempt to match any leading usernames or nicknames on the mask, using
136 * match(), when match_with_username is true.
138 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
140 unsigned char addr_raw[16];
141 unsigned char mask_raw[16];
142 unsigned int bits = 0;
145 /* The caller is trying to match ident@<mask>/bits.
146 * Chop off the ident@ portion, use match() on it
149 if (match_with_username)
151 /* Duplicate the strings, and try to find the position
152 * of the @ symbol in each */
153 char* address_dupe = strdup(address);
154 char* cidr_dupe = strdup(cidr_mask);
156 /* Use strchr not strrchr, because its going to be nearer to the left */
157 char* username_mask_pos = strrchr(cidr_dupe, '@');
158 char* username_addr_pos = strrchr(address_dupe, '@');
160 /* Both strings have an @ symbol in them */
161 if (username_mask_pos && username_addr_pos)
163 /* Zero out the location of the @ symbol */
164 *username_mask_pos = *username_addr_pos = 0;
166 /* Try and match() the strings before the @
167 * symbols, and recursively call MatchCIDR without
168 * username matching enabled to match the host part.
170 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
172 /* Free the stuff we created */
176 /* Return a result */
181 /* One or both didnt have an @ in,
186 mask = strdup(cidr_mask);
191 /* Make a copy of the cidr mask string,
192 * we're going to change it
194 mask = strdup(cidr_mask);
201 /* Use strrchr for this, its nearer to the right */
202 char* bits_chars = strrchr(mask,'/');
206 bits = atoi(bits_chars + 1);
211 /* No 'number of bits' field! */
216 #ifdef SUPPORT_IP6LINKS
217 in6_addr address_in6;
220 if (inet_pton(AF_INET6, address, &address_in6) > 0)
222 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
224 memcpy(&addr_raw, &address_in6.s6_addr, 16);
225 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
232 /* The address was valid ipv6, but the mask
233 * that goes with it wasnt.
241 if (inet_pton(AF_INET, address, &address_in4) > 0)
243 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
245 memcpy(&addr_raw, &address_in4.s_addr, 4);
246 memcpy(&mask_raw, &mask_in4.s_addr, 4);
253 /* The address was valid ipv4,
254 * but the mask that went with it wasnt.
262 /* The address was neither ipv4 or ipv6 */
267 /* Low-level-match the bits in the raw data */
269 return MatchCIDRBits(addr_raw, mask_raw, bits);
272 void irc::sockets::Blocking(int s)
274 int flags = fcntl(s, F_GETFL, 0);
275 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
278 void irc::sockets::NonBlocking(int s)
280 int flags = fcntl(s, F_GETFL, 0);
281 fcntl(s, F_SETFL, flags | O_NONBLOCK);
284 /** This will bind a socket to a port. It works for UDP/TCP.
285 * It can only bind to IP addresses, if you wish to bind to hostnames
286 * you should first resolve them using class 'Resolver'.
288 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
290 memset(&server,0,sizeof(server));
296 if ((*addr) && (insp_aton(addr,&addy) < 1))
300 server.sin6_family = AF_FAMILY;
302 server.sin_family = AF_FAMILY;
307 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
309 server.sin_addr.s_addr = htonl(INADDR_ANY);
315 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
317 server.sin_addr = addy;
321 server.sin6_port = htons(port);
323 server.sin_port = htons(port);
325 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
331 if (listen(sockfd, Config->MaxConn) == -1)
333 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
346 int irc::sockets::OpenTCPSocket()
350 struct linger linger = { 0 };
352 if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
358 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
359 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
362 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
367 /* XXX: Probably belongs in class InspIRCd */
368 bool InspIRCd::HasPort(int port, char* addr)
370 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
372 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
380 /* XXX: Probably belongs in class InspIRCd */
381 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
383 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
384 insp_sockaddr client, server;
385 int clientportcount = 0;
386 int BoundPortCount = 0;
390 int InitialPortCount = stats->BoundPortCount;
392 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
394 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
395 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
396 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
398 if ((!*Type) || (!strcmp(Type,"clients")))
400 irc::portparser portrange(configToken, false);
402 while ((portno = portrange.GetToken()))
404 if (!HasPort(portno, Addr))
407 Config->ports[clientportcount+InitialPortCount] = portno;
411 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
419 int PortCount = clientportcount;
422 BoundPortCount = stats->BoundPortCount;
423 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
425 int fd = OpenTCPSocket();
428 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
432 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
433 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
435 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
437 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
438 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
439 close(Config->openSockfd[BoundPortCount]->GetFd());
440 delete Config->openSockfd[BoundPortCount];
441 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
448 return InitialPortCount + BoundPortCount;
450 return InitialPortCount;
454 int PortCount = clientportcount;
456 for (int count = 0; count < PortCount; count++)
458 int fd = OpenTCPSocket();
461 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
465 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
466 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
471 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
474 return BoundPortCount;
477 const char* irc::sockets::insp_ntoa(insp_inaddr n)
479 static char buf[1024];
480 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
484 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
486 return inet_pton(AF_FAMILY, a, n);