]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
Just comments
[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 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
68 bool MatchCIDR(const char* address, const char* cidr_mask)
69 {
70         return MatchCIDR(address, cidr_mask, false);
71 }
72
73 /* 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
74  * If you have a lot of hosts to match, youre probably better off building your mask once
75  * and then using the lower level MatchCIDRBits directly.
76  *
77  * This will also attempt to match any leading usernames or nicknames on the mask, using
78  * match(), when match_with_username is true.
79  */
80 bool MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
81 {
82         unsigned char addr_raw[16];
83         unsigned char mask_raw[16];
84         unsigned int bits = 0;
85         char* mask = NULL;
86
87         /* The caller is trying to match ident@<mask>/bits.
88          * Chop off the ident@ portion, use match() on it
89          * seperately.
90          */
91         if (match_with_username)
92         {
93                 /* Duplicate the strings, and try to find the position
94                  * of the @ symbol in each */
95                 char* address_dupe = strdup(address);
96                 char* cidr_dupe = strdup(cidr_mask);
97                 
98                 char* username_mask_pos = strchr(cidr_dupe, '@');
99                 char* username_addr_pos = strchr(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         char* bits_chars = strchr(mask,'/');
143
144         if (bits_chars)
145         {
146                 bits = atoi(bits_chars + 1);
147                 *bits_chars = 0;
148         }
149         else
150         {
151                 /* No 'number of bits' field! */
152                 return false;
153         }
154
155 #ifdef SUPPORT_IP6LINKS
156         in6_addr address_in6;
157         in6_addr mask_in6;
158
159         if (inet_pton(AF_INET6, address, &address_in6) > 0)
160         {
161                 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
162                 {
163                         memcpy(&addr_raw, &address_in6.s6_addr, 16);
164                         memcpy(&mask_raw, &mask_in6.s6_addr, 16);
165
166                         if (bits > 128)
167                                 bits = 128;
168                 }
169                 else
170                 {
171                         /* The address was valid ipv6, but the mask
172                          * that goes with it wasnt.
173                          */
174                         free(mask);
175                         return false;
176                 }
177         }
178         else
179 #endif
180         if (inet_pton(AF_INET, address, &address_in4) > 0)
181         {
182                 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
183                 {
184                         memcpy(&addr_raw, &address_in4.s_addr, 4);
185                         memcpy(&mask_raw, &mask_in4.s_addr, 4);
186
187                         if (bits > 32)
188                                 bits = 32;
189                 }
190                 else
191                 {
192                         /* The address was valid ipv4,
193                          * but the mask that went with it wasnt.
194                          */
195                         free(mask);
196                         return false;
197                 }
198         }
199         else
200         {
201                 /* The address was neither ipv4 or ipv6 */
202                 free(mask);
203                 return false;
204         }
205
206         /* Low-level-match the bits in the raw data */
207         free(mask);
208         return MatchCIDRBits(addr_raw, mask_raw, bits);
209 }
210
211 /** This will bind a socket to a port. It works for UDP/TCP.
212  * It can only bind to IP addresses, if you wish to bind to hostnames
213  * you should first resolve them using class 'Resolver'.
214  */ 
215 bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
216 {
217         memset(&server,0,sizeof(server));
218         insp_inaddr addy;
219
220         if (*addr == '*')
221                 *addr = 0;
222
223         if ((*addr) && (insp_aton(addr,&addy) < 1))
224         {
225                 log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
226                 return false;;
227         }
228
229 #ifdef IPV6
230         server.sin6_family = AF_FAMILY;
231 #else
232         server.sin_family = AF_FAMILY;
233 #endif
234         if (!*addr)
235         {
236 #ifdef IPV6
237                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
238 #else
239                 server.sin_addr.s_addr = htonl(INADDR_ANY);
240 #endif
241         }
242         else
243         {
244 #ifdef IPV6
245                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
246 #else
247                 server.sin_addr = addy;
248 #endif
249         }
250 #ifdef IPV6
251         server.sin6_port = htons(port);
252 #else
253         server.sin_port = htons(port);
254 #endif
255         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
256         {
257                 return false;
258         }
259         else
260         {
261                 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
262                 if (listen(sockfd, Config->MaxConn) == -1)
263                 {
264                         log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
265                         return false;
266                 }
267                 else
268                 {
269                         NonBlocking(sockfd);
270                         return true;
271                 }
272         }
273 }
274
275
276 // Open a TCP Socket
277 int OpenTCPSocket()
278 {
279         int sockfd;
280         int on = 1;
281         struct linger linger = { 0 };
282   
283         if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
284         {
285                 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
286                 return (ERROR);
287         }
288         else
289         {
290                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
291                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
292                 linger.l_onoff = 1;
293                 linger.l_linger = 1;
294                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
295                 return (sockfd);
296         }
297 }
298
299 bool HasPort(int port, char* addr)
300 {
301         for (unsigned long count = 0; count < ServerInstance->stats->BoundPortCount; count++)
302         {
303                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
304                 {
305                         return true;
306                 }
307         }
308         return false;
309 }
310
311 int BindPorts(bool bail)
312 {
313         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
314         insp_sockaddr client, server;
315         int clientportcount = 0;
316         int BoundPortCount = 0;
317
318         if (!bail)
319         {
320                 int InitialPortCount = ServerInstance->stats->BoundPortCount;
321                 log(DEBUG,"Initial port count: %d",InitialPortCount);
322
323                 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
324                 {
325                         Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
326                         Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
327                         Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
328
329                         if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
330                         {
331                                 // modules handle server bind types now
332                                 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
333                                 if (*Addr == '*')
334                                         *Addr = 0;
335
336                                 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
337                                 clientportcount++;
338                                 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
339                         }
340                 }
341                 int PortCount = clientportcount;
342                 if (PortCount)
343                 {
344                         for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
345                         {
346                                 if ((Config->openSockfd[count] = OpenTCPSocket()) == ERROR)
347                                 {
348                                         log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[count],Config->addrs[count],Config->ports[count]);
349                                         return ERROR;
350                                 }
351                                 if (!BindSocket(Config->openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
352                                 {
353                                         log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
354                                 }
355                                 else
356                                 {
357                                         /* Associate the new open port with a slot in the socket engine */
358                                         if (Config->openSockfd[count] > -1)
359                                         {
360                                                 ServerInstance->SE->AddFd(Config->openSockfd[count],true,X_LISTEN);
361                                                 BoundPortCount++;
362                                         }
363                                 }
364                         }
365                         return InitialPortCount + BoundPortCount;
366                 }
367                 else
368                 {
369                         log(DEBUG,"There is nothing new to bind!");
370                 }
371                 return InitialPortCount;
372         }
373
374         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
375         {
376                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
377                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
378                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
379
380                 if ((!*Type) || (!strcmp(Type,"clients")))
381                 {
382                         // modules handle server bind types now
383                         Config->ports[clientportcount] = atoi(configToken);
384
385                         // If the client put bind "*", this is an unrealism.
386                         // We don't actually support this as documented, but
387                         // i got fed up of people trying it, so now it converts
388                         // it to an empty string meaning the same 'bind to all'.
389                         if (*Addr == '*')
390                                 *Addr = 0;
391
392                         strlcpy(Config->addrs[clientportcount],Addr,256);
393                         clientportcount++;
394                         log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
395                 }
396         }
397
398         int PortCount = clientportcount;
399
400         for (int count = 0; count < PortCount; count++)
401         {
402                 if ((Config->openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
403                 {
404                         log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
405                         return ERROR;
406                 }
407
408                 if (!BindSocket(Config->openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
409                 {
410                         log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
411                 }
412                 else
413                 {
414                         /* well we at least bound to one socket so we'll continue */
415                         BoundPortCount++;
416                 }
417         }
418
419         /* if we didn't bind to anything then abort */
420         if (!BoundPortCount)
421         {
422                 log(DEFAULT,"No ports bound, bailing!");
423                 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
424                 return ERROR;
425         }
426
427         return BoundPortCount;
428 }
429
430 const char* insp_ntoa(insp_inaddr n)
431 {
432         static char buf[1024];
433         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
434         return buf;
435 }
436
437 int insp_aton(const char* a, insp_inaddr* n)
438 {
439         return inet_pton(AF_FAMILY, a, n);
440 }
441