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