]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
b45322c3d182ebb58c5a77409f3bab2f0837cba2
[user/henk/code/inspircd.git] / src / socket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <string>
18 #include "configreader.h"
19 #include "socket.h"
20 #include "inspircd.h"
21 #include "inspstring.h"
22 #include "helperfuncs.h"
23 #include "socketengine.h"
24 #include "message.h"
25
26 extern InspIRCd* ServerInstance;
27 extern ServerConfig* Config;
28 extern time_t TIME;
29
30 /* Used when comparing CIDR masks for the modulus bits left over */
31
32 char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits */
33                           0x80, /* 10000000 - 1 bits */
34                           0xC0, /* 11000000 - 2 bits */
35                           0xE0, /* 11100000 - 3 bits */
36                           0xF0, /* 11110000 - 4 bits */
37                           0xF8, /* 11111000 - 5 bits */
38                           0xFC, /* 11111100 - 6 bits */
39                           0xFE  /* 11111110 - 7 bits */
40 };
41
42 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
43 bool MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
44 {
45         unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
46         unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
47
48         /* We shouldnt match anything, /0 is always valid */
49         if (!mask_bits)
50                 return true;
51
52         /* First compare the whole bytes, if they dont match, return false */
53         if (memcmp(address, mask, divisor))
54                 return false;
55
56         /* Now if there are any remainder bits, we compare them with logic AND */
57         if (modulus)
58                 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
59                         /* If they dont match, return false */
60                         return false;
61
62         /* The address matches the mask, to mask_bits bits of mask */
63         return true;
64 }
65
66 /* 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
67  * If you have a lot of hosts to match, youre probably better off building your mask once
68  * and then using the lower level MatchCIDRBits directly.
69  */
70 bool MatchCIDR(const char* address, const char* cidr_mask)
71 {
72         unsigned char addr_raw[16];
73         unsigned char mask_raw[16];
74         unsigned int bits = 0;
75         char* mask = strdup(cidr_mask);
76
77         in_addr  address_in4;
78         in_addr  mask_in4;
79
80         char* bits_chars = strchr(mask,'/');
81
82         if (bits_chars)
83         {
84                 bits = atoi(bits_chars + 1);
85                 *bits_chars = 0;
86         }
87         else
88         {
89                 /* No 'number of bits' field! */
90                 return false;
91         }
92
93 #ifdef SUPPORT_IP6LINKS
94         in6_addr address_in6;
95         in6_addr mask_in6;
96
97         if (inet_pton(AF_INET6, address, &address_in6) > 0)
98         {
99                 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
100                 {
101                         memcpy(&addr_raw, &address_in6.s6_addr, 16);
102                         memcpy(&mask_raw, &mask_in6.s6_addr, 16);
103
104                         if (bits > 128)
105                                 bits = 128;
106                 }
107                 else
108                 {
109                         free(mask);
110                         return false;
111                 }
112         }
113         else
114 #endif
115         if (inet_pton(AF_INET, address, &address_in4) > 0)
116         {
117                 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
118                 {
119                         memcpy(&addr_raw, &address_in4.s_addr, 4);
120                         memcpy(&mask_raw, &mask_in4.s_addr, 4);
121
122                         if (bits > 32)
123                                 bits = 32;
124                 }
125                 else
126                 {
127                         free(mask);
128                         return false;
129                 }
130         }
131         else
132         {
133                 free(mask);
134                 return false;
135         }
136
137         free(mask);
138         return MatchCIDRBits(addr_raw, mask_raw, bits);
139 }
140
141 /** This will bind a socket to a port. It works for UDP/TCP.
142  * It can only bind to IP addresses, if you wish to bind to hostnames
143  * you should first resolve them using class 'Resolver'.
144  */ 
145 bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
146 {
147         memset(&server,0,sizeof(server));
148         insp_inaddr addy;
149
150         if (*addr == '*')
151                 *addr = 0;
152
153         if ((*addr) && (insp_aton(addr,&addy) < 1))
154         {
155                 log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
156                 return false;;
157         }
158
159 #ifdef IPV6
160         server.sin6_family = AF_FAMILY;
161 #else
162         server.sin_family = AF_FAMILY;
163 #endif
164         if (!*addr)
165         {
166 #ifdef IPV6
167                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
168 #else
169                 server.sin_addr.s_addr = htonl(INADDR_ANY);
170 #endif
171         }
172         else
173         {
174 #ifdef IPV6
175                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
176 #else
177                 server.sin_addr = addy;
178 #endif
179         }
180 #ifdef IPV6
181         server.sin6_port = htons(port);
182 #else
183         server.sin_port = htons(port);
184 #endif
185         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
186         {
187                 return false;
188         }
189         else
190         {
191                 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
192                 if (listen(sockfd, Config->MaxConn) == -1)
193                 {
194                         log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
195                         return false;
196                 }
197                 else
198                 {
199                         NonBlocking(sockfd);
200                         return true;
201                 }
202         }
203 }
204
205
206 // Open a TCP Socket
207 int OpenTCPSocket()
208 {
209         int sockfd;
210         int on = 1;
211         struct linger linger = { 0 };
212   
213         if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
214         {
215                 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
216                 return (ERROR);
217         }
218         else
219         {
220                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
221                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
222                 linger.l_onoff = 1;
223                 linger.l_linger = 1;
224                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
225                 return (sockfd);
226         }
227 }
228
229 bool HasPort(int port, char* addr)
230 {
231         for (unsigned long count = 0; count < ServerInstance->stats->BoundPortCount; count++)
232         {
233                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
234                 {
235                         return true;
236                 }
237         }
238         return false;
239 }
240
241 int BindPorts(bool bail)
242 {
243         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
244         insp_sockaddr client, server;
245         int clientportcount = 0;
246         int BoundPortCount = 0;
247
248         if (!bail)
249         {
250                 int InitialPortCount = ServerInstance->stats->BoundPortCount;
251                 log(DEBUG,"Initial port count: %d",InitialPortCount);
252
253                 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
254                 {
255                         Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
256                         Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
257                         Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
258
259                         if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
260                         {
261                                 // modules handle server bind types now
262                                 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
263                                 if (*Addr == '*')
264                                         *Addr = 0;
265
266                                 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
267                                 clientportcount++;
268                                 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
269                         }
270                 }
271                 int PortCount = clientportcount;
272                 if (PortCount)
273                 {
274                         for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
275                         {
276                                 if ((Config->openSockfd[count] = OpenTCPSocket()) == ERROR)
277                                 {
278                                         log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[count],Config->addrs[count],Config->ports[count]);
279                                         return ERROR;
280                                 }
281                                 if (!BindSocket(Config->openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
282                                 {
283                                         log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
284                                 }
285                                 else
286                                 {
287                                         /* Associate the new open port with a slot in the socket engine */
288                                         if (Config->openSockfd[count] > -1)
289                                         {
290                                                 ServerInstance->SE->AddFd(Config->openSockfd[count],true,X_LISTEN);
291                                                 BoundPortCount++;
292                                         }
293                                 }
294                         }
295                         return InitialPortCount + BoundPortCount;
296                 }
297                 else
298                 {
299                         log(DEBUG,"There is nothing new to bind!");
300                 }
301                 return InitialPortCount;
302         }
303
304         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
305         {
306                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
307                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
308                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
309
310                 if ((!*Type) || (!strcmp(Type,"clients")))
311                 {
312                         // modules handle server bind types now
313                         Config->ports[clientportcount] = atoi(configToken);
314
315                         // If the client put bind "*", this is an unrealism.
316                         // We don't actually support this as documented, but
317                         // i got fed up of people trying it, so now it converts
318                         // it to an empty string meaning the same 'bind to all'.
319                         if (*Addr == '*')
320                                 *Addr = 0;
321
322                         strlcpy(Config->addrs[clientportcount],Addr,256);
323                         clientportcount++;
324                         log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
325                 }
326         }
327
328         int PortCount = clientportcount;
329
330         for (int count = 0; count < PortCount; count++)
331         {
332                 if ((Config->openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
333                 {
334                         log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
335                         return ERROR;
336                 }
337
338                 if (!BindSocket(Config->openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
339                 {
340                         log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
341                 }
342                 else
343                 {
344                         /* well we at least bound to one socket so we'll continue */
345                         BoundPortCount++;
346                 }
347         }
348
349         /* if we didn't bind to anything then abort */
350         if (!BoundPortCount)
351         {
352                 log(DEFAULT,"No ports bound, bailing!");
353                 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
354                 return ERROR;
355         }
356
357         return BoundPortCount;
358 }
359
360 const char* insp_ntoa(insp_inaddr n)
361 {
362         static char buf[1024];
363         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
364         return buf;
365 }
366
367 int insp_aton(const char* a, insp_inaddr* n)
368 {
369         return inet_pton(AF_FAMILY, a, n);
370 }
371