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