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)
42 Instance->Log(DEBUG,"Binding to port %s:%d",addr,port);
43 if (!Instance->BindSocket(this->fd,client,server,port,addr))
45 Instance->Log(DEBUG,"Binding failed!");
50 void ListenSocket::HandleEvent(EventType et, int errornum)
52 insp_sockaddr sock_us; // our port number
53 socklen_t uslen; // length of our port number
56 int incomingSockfd, in_port;
58 ServerInstance->Log(DEBUG,"Handle ListenSocket event");
60 uslen = sizeof(sock_us);
61 length = sizeof(client);
62 incomingSockfd = accept (this->GetFd(),(struct sockaddr*)&client, &length);
64 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, (sockaddr*)&sock_us, &uslen)))
67 in_port = ntohs(sock_us.sin6_port);
69 in_port = ntohs(sock_us.sin_port);
71 ServerInstance->Log(DEBUG,"Accepted socket %d",incomingSockfd);
72 NonBlocking(incomingSockfd);
73 if (ServerInstance->Config->GetIOHook(in_port))
78 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
80 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
83 catch (CoreException& modexcept)
85 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
88 ServerInstance->stats->statsAccept++;
90 ServerInstance->Log(DEBUG,"Add ipv6 client");
91 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin6_addr);
93 ServerInstance->Log(DEBUG,"Add ipv4 client");
94 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin_addr);
96 ServerInstance->Log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
100 ServerInstance->Log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
101 shutdown(incomingSockfd,2);
102 close(incomingSockfd);
103 ServerInstance->stats->statsRefused++;
107 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
108 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
110 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
111 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
113 /* First compare the whole bytes, if they dont match, return false */
114 if (memcmp(address, mask, divisor))
117 /* Now if there are any remainder bits, we compare them with logic AND */
119 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
120 /* If they dont match, return false */
123 /* The address matches the mask, to mask_bits bits of mask */
127 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
128 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
130 return MatchCIDR(address, cidr_mask, false);
133 /* 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
134 * If you have a lot of hosts to match, youre probably better off building your mask once
135 * and then using the lower level MatchCIDRBits directly.
137 * This will also attempt to match any leading usernames or nicknames on the mask, using
138 * match(), when match_with_username is true.
140 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
142 unsigned char addr_raw[16];
143 unsigned char mask_raw[16];
144 unsigned int bits = 0;
147 /* The caller is trying to match ident@<mask>/bits.
148 * Chop off the ident@ portion, use match() on it
151 if (match_with_username)
153 /* Duplicate the strings, and try to find the position
154 * of the @ symbol in each */
155 char* address_dupe = strdup(address);
156 char* cidr_dupe = strdup(cidr_mask);
158 /* Use strchr not strrchr, because its going to be nearer to the left */
159 char* username_mask_pos = strrchr(cidr_dupe, '@');
160 char* username_addr_pos = strrchr(address_dupe, '@');
162 /* Both strings have an @ symbol in them */
163 if (username_mask_pos && username_addr_pos)
165 /* Zero out the location of the @ symbol */
166 *username_mask_pos = *username_addr_pos = 0;
168 /* Try and match() the strings before the @
169 * symbols, and recursively call MatchCIDR without
170 * username matching enabled to match the host part.
172 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
174 /* Free the stuff we created */
178 /* Return a result */
183 /* One or both didnt have an @ in,
188 mask = strdup(cidr_mask);
193 /* Make a copy of the cidr mask string,
194 * we're going to change it
196 mask = strdup(cidr_mask);
203 /* Use strrchr for this, its nearer to the right */
204 char* bits_chars = strrchr(mask,'/');
208 bits = atoi(bits_chars + 1);
213 /* No 'number of bits' field! */
218 #ifdef SUPPORT_IP6LINKS
219 in6_addr address_in6;
222 if (inet_pton(AF_INET6, address, &address_in6) > 0)
224 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
226 memcpy(&addr_raw, &address_in6.s6_addr, 16);
227 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
234 /* The address was valid ipv6, but the mask
235 * that goes with it wasnt.
243 if (inet_pton(AF_INET, address, &address_in4) > 0)
245 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
247 memcpy(&addr_raw, &address_in4.s_addr, 4);
248 memcpy(&mask_raw, &mask_in4.s_addr, 4);
255 /* The address was valid ipv4,
256 * but the mask that went with it wasnt.
264 /* The address was neither ipv4 or ipv6 */
269 /* Low-level-match the bits in the raw data */
271 return MatchCIDRBits(addr_raw, mask_raw, bits);
274 inline void irc::sockets::Blocking(int s)
276 int flags = fcntl(s, F_GETFL, 0);
277 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
280 inline void irc::sockets::NonBlocking(int s)
282 int flags = fcntl(s, F_GETFL, 0);
283 fcntl(s, F_SETFL, flags | O_NONBLOCK);
287 /** This will bind a socket to a port. It works for UDP/TCP.
288 * It can only bind to IP addresses, if you wish to bind to hostnames
289 * you should first resolve them using class 'Resolver'.
291 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
293 memset(&server,0,sizeof(server));
299 if ((*addr) && (insp_aton(addr,&addy) < 1))
301 this->Log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
306 server.sin6_family = AF_FAMILY;
308 server.sin_family = AF_FAMILY;
313 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
315 server.sin_addr.s_addr = htonl(INADDR_ANY);
321 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
323 server.sin_addr = addy;
327 server.sin6_port = htons(port);
329 server.sin_port = htons(port);
331 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
337 this->Log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
338 if (listen(sockfd, Config->MaxConn) == -1)
340 this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
353 int irc::sockets::OpenTCPSocket()
357 struct linger linger = { 0 };
359 if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
365 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
366 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
369 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
374 /* XXX: Probably belongs in class InspIRCd */
375 bool InspIRCd::HasPort(int port, char* addr)
377 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
379 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
387 /* XXX: Probably belongs in class InspIRCd */
388 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
390 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
391 insp_sockaddr client, server;
392 int clientportcount = 0;
393 int BoundPortCount = 0;
397 int InitialPortCount = stats->BoundPortCount;
398 this->Log(DEBUG,"Initial port count: %d",InitialPortCount);
400 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
402 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
403 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
404 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
406 if ((!*Type) || (!strcmp(Type,"clients")))
408 irc::portparser portrange(configToken, false);
410 while ((portno = portrange.GetToken()))
412 if (!HasPort(portno, Addr))
415 Config->ports[clientportcount+InitialPortCount] = portno;
419 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
421 this->Log(DEBUG,"NEW binding %s:%d [%s] from config",Addr, portno, Type);
428 int PortCount = clientportcount;
431 BoundPortCount = stats->BoundPortCount;
432 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
434 int fd = OpenTCPSocket();
437 this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
438 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
442 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
443 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
445 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
447 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
448 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
449 close(Config->openSockfd[BoundPortCount]->GetFd());
450 delete Config->openSockfd[BoundPortCount];
451 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
458 return InitialPortCount + BoundPortCount;
462 this->Log(DEBUG,"There is nothing new to bind!");
464 return InitialPortCount;
468 int PortCount = clientportcount;
470 for (int count = 0; count < PortCount; count++)
472 int fd = OpenTCPSocket();
475 this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
476 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
480 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
481 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
486 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
489 return BoundPortCount;
492 const char* irc::sockets::insp_ntoa(insp_inaddr n)
494 static char buf[1024];
495 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
499 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
501 return inet_pton(AF_FAMILY, a, n);