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 shutdown(this->fd, 2);
64 void ListenSocket::HandleEvent(EventType et, int errornum)
66 sockaddr* sock_us = new sockaddr[2]; // our port number
67 sockaddr* client = new sockaddr[2];
68 socklen_t uslen, length; // length of our port number
69 int incomingSockfd, in_port;
72 if (this->family == AF_INET6)
74 uslen = sizeof(sockaddr_in6);
75 length = sizeof(sockaddr_in6);
79 uslen = sizeof(sockaddr_in);
80 length = sizeof(sockaddr_in);
83 uslen = sizeof(sockaddr_in);
84 length = sizeof(sockaddr_in);
86 incomingSockfd = accept (this->GetFd(), (sockaddr*)client, &length);
88 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, 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);
99 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
100 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
103 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
104 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
106 NonBlocking(incomingSockfd);
107 if (ServerInstance->Config->GetIOHook(in_port))
111 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, buf, in_port);
113 catch (CoreException& modexcept)
115 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
118 ServerInstance->stats->statsAccept++;
119 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, this->family, client);
123 shutdown(incomingSockfd,2);
124 close(incomingSockfd);
125 ServerInstance->stats->statsRefused++;
131 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
132 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
134 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
135 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
137 /* First compare the whole bytes, if they dont match, return false */
138 if (memcmp(address, mask, divisor))
141 /* Now if there are any remainder bits, we compare them with logic AND */
143 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
144 /* If they dont match, return false */
147 /* The address matches the mask, to mask_bits bits of mask */
151 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
152 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
154 return MatchCIDR(address, cidr_mask, false);
157 /* 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
158 * If you have a lot of hosts to match, youre probably better off building your mask once
159 * and then using the lower level MatchCIDRBits directly.
161 * This will also attempt to match any leading usernames or nicknames on the mask, using
162 * match(), when match_with_username is true.
164 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
166 unsigned char addr_raw[16];
167 unsigned char mask_raw[16];
168 unsigned int bits = 0;
171 /* The caller is trying to match ident@<mask>/bits.
172 * Chop off the ident@ portion, use match() on it
175 if (match_with_username)
177 /* Duplicate the strings, and try to find the position
178 * of the @ symbol in each */
179 char* address_dupe = strdup(address);
180 char* cidr_dupe = strdup(cidr_mask);
182 /* Use strchr not strrchr, because its going to be nearer to the left */
183 char* username_mask_pos = strrchr(cidr_dupe, '@');
184 char* username_addr_pos = strrchr(address_dupe, '@');
186 /* Both strings have an @ symbol in them */
187 if (username_mask_pos && username_addr_pos)
189 /* Zero out the location of the @ symbol */
190 *username_mask_pos = *username_addr_pos = 0;
192 /* Try and match() the strings before the @
193 * symbols, and recursively call MatchCIDR without
194 * username matching enabled to match the host part.
196 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
198 /* Free the stuff we created */
202 /* Return a result */
207 /* One or both didnt have an @ in,
212 mask = strdup(cidr_mask);
217 /* Make a copy of the cidr mask string,
218 * we're going to change it
220 mask = strdup(cidr_mask);
227 /* Use strrchr for this, its nearer to the right */
228 char* bits_chars = strrchr(mask,'/');
232 bits = atoi(bits_chars + 1);
237 /* No 'number of bits' field! */
242 #ifdef SUPPORT_IP6LINKS
243 in6_addr address_in6;
246 if (inet_pton(AF_INET6, address, &address_in6) > 0)
248 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
250 memcpy(&addr_raw, &address_in6.s6_addr, 16);
251 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
258 /* The address was valid ipv6, but the mask
259 * that goes with it wasnt.
267 if (inet_pton(AF_INET, address, &address_in4) > 0)
269 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
271 memcpy(&addr_raw, &address_in4.s_addr, 4);
272 memcpy(&mask_raw, &mask_in4.s_addr, 4);
279 /* The address was valid ipv4,
280 * but the mask that went with it wasnt.
288 /* The address was neither ipv4 or ipv6 */
293 /* Low-level-match the bits in the raw data */
295 return MatchCIDRBits(addr_raw, mask_raw, bits);
298 void irc::sockets::Blocking(int s)
300 int flags = fcntl(s, F_GETFL, 0);
301 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
304 void irc::sockets::NonBlocking(int s)
306 int flags = fcntl(s, F_GETFL, 0);
307 fcntl(s, F_SETFL, flags | O_NONBLOCK);
310 /** This will bind a socket to a port. It works for UDP/TCP.
311 * It can only bind to IP addresses, if you wish to bind to hostnames
312 * you should first resolve them using class 'Resolver'.
314 bool InspIRCd::BindSocket(int sockfd, int port, char* addr, bool dolisten)
316 /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
317 sockaddr* server = new sockaddr[2];
318 memset(server,0,sizeof(sockaddr)*2);
328 /* There is an address here. Is it ipv6? */
329 if (strchr(addr,':'))
333 if (inet_pton(AF_INET6, addr, &addy) < 1)
339 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
340 memcpy(&(((sockaddr_in6*)server)->sin6_addr), &addy, sizeof(in6_addr));
341 ((sockaddr_in6*)server)->sin6_port = htons(port);
342 size = sizeof(sockaddr_in6);
348 if (inet_pton(AF_INET, addr, &addy) < 1)
354 ((sockaddr_in*)server)->sin_family = AF_INET;
355 ((sockaddr_in*)server)->sin_addr = addy;
356 ((sockaddr_in*)server)->sin_port = htons(port);
357 size = sizeof(sockaddr_in);
364 /* Port -1: Means UDP IPV4 port binding - Special case
365 * used by DNS engine.
367 ((sockaddr_in*)server)->sin_family = AF_INET;
368 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
369 ((sockaddr_in*)server)->sin_port = 0;
370 size = sizeof(sockaddr_in);
374 /* Theres no address here, default to ipv6 bind to all */
375 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
376 memset(&(((sockaddr_in6*)server)->sin6_addr), 0, sizeof(in6_addr));
377 ((sockaddr_in6*)server)->sin6_port = htons(port);
378 size = sizeof(sockaddr_in6);
382 /* If we aren't built with ipv6, the choice becomes simple */
383 ((sockaddr_in*)server)->sin_family = AF_INET;
386 /* There is an address here. */
388 if (inet_pton(AF_INET, addr, &addy) < 1)
393 ((sockaddr_in*)server)->sin_addr = addy;
397 /* Bind ipv4 to all */
398 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
400 /* Bind ipv4 port number */
401 ((sockaddr_in*)server)->sin_port = htons(port);
402 size = sizeof(sockaddr_in);
404 ret = bind(sockfd, server, size);
415 if (listen(sockfd, Config->MaxConn) == -1)
417 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
434 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
438 struct linger linger = { 0 };
440 if (strchr(addr,':') || (!*addr))
441 sockfd = socket (PF_INET6, socktype, 0);
443 sockfd = socket (PF_INET, socktype, 0);
446 if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
453 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
454 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
457 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
462 /* XXX: Probably belongs in class InspIRCd */
463 bool InspIRCd::HasPort(int port, char* addr)
465 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
467 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
475 /* XXX: Probably belongs in class InspIRCd */
476 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
478 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
479 insp_sockaddr client, server;
480 int clientportcount = 0;
481 int BoundPortCount = 0;
485 int InitialPortCount = stats->BoundPortCount;
487 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
489 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
490 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
491 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
493 if ((!*Type) || (!strcmp(Type,"clients")))
495 irc::portparser portrange(configToken, false);
497 while ((portno = portrange.GetToken()))
499 if (!HasPort(portno, Addr))
502 Config->ports[clientportcount+InitialPortCount] = portno;
506 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
514 int PortCount = clientportcount;
517 BoundPortCount = stats->BoundPortCount;
518 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
520 int fd = OpenTCPSocket(Config->addrs[count]);
523 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
527 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
528 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
530 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
532 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
533 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
534 close(Config->openSockfd[BoundPortCount]->GetFd());
535 delete Config->openSockfd[BoundPortCount];
536 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
543 return InitialPortCount + BoundPortCount;
545 return InitialPortCount;
549 int PortCount = clientportcount;
551 for (int count = 0; count < PortCount; count++)
553 int fd = OpenTCPSocket(Config->addrs[count]);
556 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
560 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
561 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
566 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
569 return BoundPortCount;
572 const char* irc::sockets::insp_ntoa(insp_inaddr n)
574 static char buf[1024];
575 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
579 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
581 return inet_pton(AF_FAMILY, a, n);