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