1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
18 #include "configreader.h"
21 #include "inspstring.h"
22 #include "helperfuncs.h"
23 #include "socketengine.h"
27 extern InspIRCd* ServerInstance;
30 /* Used when comparing CIDR masks for the modulus bits left over.
31 * A lot of ircd's seem to do this:
32 * ((-1) << (8 - (mask % 8)))
33 * But imho, it sucks in comparison to a nice neat lookup table.
35 const char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
36 0x80, /* 10000000 - 1 bits */
37 0xC0, /* 11000000 - 2 bits */
38 0xE0, /* 11100000 - 3 bits */
39 0xF0, /* 11110000 - 4 bits */
40 0xF8, /* 11111000 - 5 bits */
41 0xFC, /* 11111100 - 6 bits */
42 0xFE /* 11111110 - 7 bits */
45 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
46 bool MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
48 unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
49 unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
51 /* First compare the whole bytes, if they dont match, return false */
52 if (memcmp(address, mask, divisor))
55 /* Now if there are any remainder bits, we compare them with logic AND */
57 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
58 /* If they dont match, return false */
61 /* The address matches the mask, to mask_bits bits of mask */
65 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
66 bool MatchCIDR(const char* address, const char* cidr_mask)
68 return MatchCIDR(address, cidr_mask, false);
71 /* 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
72 * If you have a lot of hosts to match, youre probably better off building your mask once
73 * and then using the lower level MatchCIDRBits directly.
75 * This will also attempt to match any leading usernames or nicknames on the mask, using
76 * match(), when match_with_username is true.
78 bool MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
80 unsigned char addr_raw[16];
81 unsigned char mask_raw[16];
82 unsigned int bits = 0;
85 /* The caller is trying to match ident@<mask>/bits.
86 * Chop off the ident@ portion, use match() on it
89 if (match_with_username)
91 /* Duplicate the strings, and try to find the position
92 * of the @ symbol in each */
93 char* address_dupe = strdup(address);
94 char* cidr_dupe = strdup(cidr_mask);
96 /* Use strchr not strrchr, because its going to be nearer to the left */
97 char* username_mask_pos = strrchr(cidr_dupe, '@');
98 char* username_addr_pos = strrchr(address_dupe, '@');
100 /* Both strings have an @ symbol in them */
101 if (username_mask_pos && username_addr_pos)
103 /* Zero out the location of the @ symbol */
104 *username_mask_pos = *username_addr_pos = 0;
106 /* Try and match() the strings before the @
107 * symbols, and recursively call MatchCIDR without
108 * username matching enabled to match the host part.
110 bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
112 /* Free the stuff we created */
116 /* Return a result */
121 /* One or both didnt have an @ in,
126 mask = strdup(cidr_mask);
131 /* Make a copy of the cidr mask string,
132 * we're going to change it
134 mask = strdup(cidr_mask);
141 /* Use strrchr for this, its nearer to the right */
142 char* bits_chars = strrchr(mask,'/');
146 bits = atoi(bits_chars + 1);
151 /* No 'number of bits' field! */
155 #ifdef SUPPORT_IP6LINKS
156 in6_addr address_in6;
159 if (inet_pton(AF_INET6, address, &address_in6) > 0)
161 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
163 memcpy(&addr_raw, &address_in6.s6_addr, 16);
164 memcpy(&mask_raw, &mask_in6.s6_addr, 16);
171 /* The address was valid ipv6, but the mask
172 * that goes with it wasnt.
180 if (inet_pton(AF_INET, address, &address_in4) > 0)
182 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
184 memcpy(&addr_raw, &address_in4.s_addr, 4);
185 memcpy(&mask_raw, &mask_in4.s_addr, 4);
192 /* The address was valid ipv4,
193 * but the mask that went with it wasnt.
201 /* The address was neither ipv4 or ipv6 */
206 /* Low-level-match the bits in the raw data */
208 return MatchCIDRBits(addr_raw, mask_raw, bits);
211 inline void Blocking(int s)
213 int flags = fcntl(s, F_GETFL, 0);
214 fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
217 inline void NonBlocking(int s)
219 int flags = fcntl(s, F_GETFL, 0);
220 fcntl(s, F_SETFL, flags | O_NONBLOCK);
224 /** This will bind a socket to a port. It works for UDP/TCP.
225 * It can only bind to IP addresses, if you wish to bind to hostnames
226 * you should first resolve them using class 'Resolver'.
228 bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
230 memset(&server,0,sizeof(server));
236 if ((*addr) && (insp_aton(addr,&addy) < 1))
238 log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
243 server.sin6_family = AF_FAMILY;
245 server.sin_family = AF_FAMILY;
250 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
252 server.sin_addr.s_addr = htonl(INADDR_ANY);
258 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
260 server.sin_addr = addy;
264 server.sin6_port = htons(port);
266 server.sin_port = htons(port);
268 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
274 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
275 if (listen(sockfd, ServerInstance->Config->MaxConn) == -1)
277 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
294 struct linger linger = { 0 };
296 if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
298 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
303 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
304 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
307 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
312 bool HasPort(int port, char* addr)
314 ServerConfig* Config = ServerInstance->Config;
315 for (unsigned long count = 0; count < ServerInstance->stats->BoundPortCount; count++)
317 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
325 int BindPorts(bool bail)
327 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
328 insp_sockaddr client, server;
329 int clientportcount = 0;
330 int BoundPortCount = 0;
331 ServerConfig* Config = ServerInstance->Config;
335 int InitialPortCount = ServerInstance->stats->BoundPortCount;
336 log(DEBUG,"Initial port count: %d",InitialPortCount);
338 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
340 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
341 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
342 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
344 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
346 // modules handle server bind types now
347 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
351 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
353 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
356 int PortCount = clientportcount;
359 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
361 if ((Config->openSockfd[count] = OpenTCPSocket()) == ERROR)
363 log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[count],Config->addrs[count],Config->ports[count]);
367 if (!BindSocket(Config->openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
369 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
373 /* Associate the new open port with a slot in the socket engine */
374 if (Config->openSockfd[count] > -1)
376 if (!ServerInstance->SE->AddFd(Config->openSockfd[count],true,X_LISTEN))
378 log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
379 shutdown(Config->openSockfd[count],2);
380 close(Config->openSockfd[count]);
388 return InitialPortCount + BoundPortCount;
392 log(DEBUG,"There is nothing new to bind!");
394 return InitialPortCount;
397 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
399 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
400 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
401 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
403 if ((!*Type) || (!strcmp(Type,"clients")))
405 // modules handle server bind types now
406 Config->ports[clientportcount] = atoi(configToken);
408 // If the client put bind "*", this is an unrealism.
409 // We don't actually support this as documented, but
410 // i got fed up of people trying it, so now it converts
411 // it to an empty string meaning the same 'bind to all'.
415 strlcpy(Config->addrs[clientportcount],Addr,256);
417 log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
421 int PortCount = clientportcount;
423 for (int count = 0; count < PortCount; count++)
425 if ((Config->openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
427 log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
431 if (!BindSocket(Config->openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
433 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
437 /* well we at least bound to one socket so we'll continue */
442 return BoundPortCount;
445 const char* insp_ntoa(insp_inaddr n)
447 static char buf[1024];
448 inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
452 int insp_aton(const char* a, insp_inaddr* n)
454 return inet_pton(AF_FAMILY, a, n);