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,port,addr))
45 if ((!*addr) || (strchr(addr,':')))
46 this->family = AF_INET6;
48 this->family = AF_INET;
50 this->family = AF_INET;
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 (shutdown(this->fd, 2) || close(this->fd))
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);
81 uslen = sizeof(sockaddr_in);
82 length = sizeof(sockaddr_in);
85 uslen = sizeof(sockaddr_in);
86 length = sizeof(sockaddr_in);
88 incomingSockfd = accept (this->GetFd(), (sockaddr*)client, &length);
90 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, sock_us, &uslen)))
94 if (this->family == AF_INET6)
96 inet_ntop(AF_INET6, &((const sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
97 in_port = ntohs(((sockaddr_in6*)sock_us)->sin6_port);
101 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
102 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
105 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
106 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
108 NonBlocking(incomingSockfd);
109 if (ServerInstance->Config->GetIOHook(in_port))
113 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, buf, in_port);
115 catch (CoreException& modexcept)
117 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
120 ServerInstance->stats->statsAccept++;
121 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, this->family, client);
125 shutdown(incomingSockfd,2);
126 close(incomingSockfd);
127 ServerInstance->stats->statsRefused++;
133 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
134 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
136 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
137 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
139 /* First compare the whole bytes, if they dont match, return false */
140 if (memcmp(address, mask, divisor))
143 /* Now if there are any remainder bits, we compare them with logic AND */
145 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
146 /* If they dont match, return false */
149 /* The address matches the mask, to mask_bits bits of mask */
153 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
154 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
156 return MatchCIDR(address, cidr_mask, false);
159 /* 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
160 * If you have a lot of hosts to match, youre probably better off building your mask once
161 * and then using the lower level MatchCIDRBits directly.
163 * This will also attempt to match any leading usernames or nicknames on the mask, using
164 * match(), when match_with_username is true.
166 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
168 unsigned char addr_raw[16];
169 unsigned char mask_raw[16];
170 unsigned int bits = 0;
173 /* The caller is trying to match ident@<mask>/bits.
174 * Chop off the ident@ portion, use match() on it
177 if (match_with_username)
179 /* Duplicate the strings, and try to find the position
180 * of the @ symbol in each */
181 char* address_dupe = strdup(address);
182 char* cidr_dupe = strdup(cidr_mask);
184 /* Use strchr not strrchr, because its going to be nearer to the left */
185 char* username_mask_pos = strrchr(cidr_dupe, '@');
186 char* username_addr_pos = strrchr(address_dupe, '@');
188 /* Both strings have an @ symbol in them */
189 if (username_mask_pos && username_addr_pos)
191 /* Zero out the location of the @ symbol */
192 *username_mask_pos = *username_addr_pos = 0;
194 /* Try and match() the strings before the @
195 * symbols, and recursively call MatchCIDR without
196 * username matching enabled to match the host part.
198 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
200 /* Free the stuff we created */
204 /* Return a result */
209 /* One or both didnt have an @ in,
214 mask = strdup(cidr_mask);
219 /* Make a copy of the cidr mask string,
220 * we're going to change it
222 mask = strdup(cidr_mask);
229 /* Use strrchr for this, its nearer to the right */
230 char* bits_chars = strrchr(mask,'/');
234 bits = atoi(bits_chars + 1);
239 /* No 'number of bits' field! */
244 #ifdef SUPPORT_IP6LINKS
245 in6_addr address_in6;
248 if (inet_pton(AF_INET6, address, &address_in6) > 0)
250 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
252 memcpy(&addr_raw, &address_in6.s6_addr, 16);
253 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
260 /* The address was valid ipv6, but the mask
261 * that goes with it wasnt.
269 if (inet_pton(AF_INET, address, &address_in4) > 0)
271 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
273 memcpy(&addr_raw, &address_in4.s_addr, 4);
274 memcpy(&mask_raw, &mask_in4.s_addr, 4);
281 /* The address was valid ipv4,
282 * but the mask that went with it wasnt.
290 /* The address was neither ipv4 or ipv6 */
295 /* Low-level-match the bits in the raw data */
297 return MatchCIDRBits(addr_raw, mask_raw, bits);
300 void irc::sockets::Blocking(int s)
302 int flags = fcntl(s, F_GETFL, 0);
303 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
306 void irc::sockets::NonBlocking(int s)
308 int flags = fcntl(s, F_GETFL, 0);
309 fcntl(s, F_SETFL, flags | O_NONBLOCK);
312 /** This will bind a socket to a port. It works for UDP/TCP.
313 * It can only bind to IP addresses, if you wish to bind to hostnames
314 * you should first resolve them using class 'Resolver'.
316 bool InspIRCd::BindSocket(int sockfd, int port, char* addr, bool dolisten)
318 /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
319 sockaddr* server = new sockaddr[2];
320 memset(server,0,sizeof(sockaddr)*2);
330 /* There is an address here. Is it ipv6? */
331 if (strchr(addr,':'))
335 if (inet_pton(AF_INET6, addr, &addy) < 1)
341 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
342 memcpy(&(((sockaddr_in6*)server)->sin6_addr), &addy, sizeof(in6_addr));
343 ((sockaddr_in6*)server)->sin6_port = htons(port);
344 size = sizeof(sockaddr_in6);
350 if (inet_pton(AF_INET, addr, &addy) < 1)
356 ((sockaddr_in*)server)->sin_family = AF_INET;
357 ((sockaddr_in*)server)->sin_addr = addy;
358 ((sockaddr_in*)server)->sin_port = htons(port);
359 size = sizeof(sockaddr_in);
366 /* Port -1: Means UDP IPV4 port binding - Special case
367 * used by DNS engine.
369 ((sockaddr_in*)server)->sin_family = AF_INET;
370 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
371 ((sockaddr_in*)server)->sin_port = 0;
372 size = sizeof(sockaddr_in);
376 /* Theres no address here, default to ipv6 bind to all */
377 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
378 memset(&(((sockaddr_in6*)server)->sin6_addr), 0, sizeof(in6_addr));
379 ((sockaddr_in6*)server)->sin6_port = htons(port);
380 size = sizeof(sockaddr_in6);
384 /* If we aren't built with ipv6, the choice becomes simple */
385 ((sockaddr_in*)server)->sin_family = AF_INET;
388 /* There is an address here. */
390 if (inet_pton(AF_INET, addr, &addy) < 1)
395 ((sockaddr_in*)server)->sin_addr = addy;
399 /* Bind ipv4 to all */
400 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
402 /* Bind ipv4 port number */
403 ((sockaddr_in*)server)->sin_port = htons(port);
404 size = sizeof(sockaddr_in);
406 ret = bind(sockfd, server, size);
417 if (listen(sockfd, Config->MaxConn) == -1)
419 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
424 this->Log(DEBUG,"New socket binding for %d with listen: %s:%d", sockfd, addr, port);
431 this->Log(DEBUG,"New socket binding for %d without listen: %s:%d", sockfd, addr, port);
438 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
442 struct linger linger = { 0 };
444 if (strchr(addr,':') || (!*addr))
445 sockfd = socket (PF_INET6, socktype, 0);
447 sockfd = socket (PF_INET, socktype, 0);
450 if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
457 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
458 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
461 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
466 /* XXX: Probably belongs in class InspIRCd */
467 bool InspIRCd::HasPort(int port, char* addr)
469 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
471 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
479 /* XXX: Probably belongs in class InspIRCd */
480 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
482 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
483 insp_sockaddr client, server;
484 int clientportcount = 0;
485 int BoundPortCount = 0;
489 int InitialPortCount = stats->BoundPortCount;
491 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
493 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
494 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
495 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
497 if ((!*Type) || (!strcmp(Type,"clients")))
499 irc::portparser portrange(configToken, false);
501 while ((portno = portrange.GetToken()))
503 if (!HasPort(portno, Addr))
506 Config->ports[clientportcount+InitialPortCount] = portno;
510 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
518 int PortCount = clientportcount;
521 BoundPortCount = stats->BoundPortCount;
522 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
524 int fd = OpenTCPSocket(Config->addrs[count]);
527 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
531 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
532 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
534 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
536 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
537 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
538 close(Config->openSockfd[BoundPortCount]->GetFd());
539 delete Config->openSockfd[BoundPortCount];
540 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
547 return InitialPortCount + BoundPortCount;
549 return InitialPortCount;
553 int PortCount = clientportcount;
555 for (int count = 0; count < PortCount; count++)
557 int fd = OpenTCPSocket(Config->addrs[count]);
560 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
564 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
565 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
570 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
573 return BoundPortCount;
576 const char* irc::sockets::insp_ntoa(insp_inaddr n)
578 static char buf[1024];
579 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
583 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
585 return inet_pton(AF_FAMILY, a, n);